10

WPF has the Popup class with which you can open a (small) window inside another window. This is used for example for Tooltips or ComboBoxes.

I need to find all of these popups which are currently opened inside a WPF window, so I can close them.

HerrLoesch
  • 1,023
  • 1
  • 13
  • 24
  • possible duplicate of [Force close all open popups from code](http://stackoverflow.com/questions/3885975/force-close-all-open-popups-from-code) – Lukazoid Jan 23 '13 at 12:06

2 Answers2

22

If someone still need:

  public static IEnumerable<Popup> GetOpenPopups()
  {
      return PresentationSource.CurrentSources.OfType<HwndSource>()
          .Select(h => h.RootVisual)
          .OfType<FrameworkElement>()
          .Select(f => f.Parent)
          .OfType<Popup>()
          .Where(p => p.IsOpen);
  }
xmetropol
  • 236
  • 2
  • 5
0

One way of doing this would be to navigate the Visual Tree to find all Popup objects, and close them if they're open

I have some VisualTreeHelpers on my blog that provide an example of how you can navigate the Visual Tree, although they are setup to only return a single object that matches the specified criteria, and not all objects.

You'll probably need to modify the code a bit to make sure it returns all objects, but the code I use for returning a single object looks like this:

    /// <summary>
    /// Looks for a child control within a parent by type
    /// </summary>
    public static T FindChild<T>(DependencyObject parent)
        where T : DependencyObject
    {
        // Confirm parent is valid.
        if (parent == null) return null;

        T foundChild = null;

        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(parent, i);
            // If the child is not of the request child type child
            T childType = child as T;
            if (childType == null)
            {
                // recursively drill down the tree
                foundChild = FindChild<T>(child);

                // If the child is found, break so we do not overwrite the found child.
                if (foundChild != null) break;
            }
            else
            {
                // child element found.
                foundChild = (T)child;
                break;
            }
        }
        return foundChild;
    }   

And can be called like this:

var popup = MyVisualTreeHelpers.FindChild<Popup>(MyWindow);
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • 4
    Are you sure that this works for popups? I am not sure because I thought the Popups are Win32 windows and not actual part of the visual tree. – HerrLoesch Jan 28 '13 at 12:56