Find all open popups in WPF application

WPF has a Popup class with which you can open a (small) window inside another window. This is used, for example, for hints or combo boxes.

I need to find all these popups that are currently opening in a WPF window, so I can close them.

+3


source to share


2 answers


If anyone still needs:



  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);
  }

      

+7


source


One way to do this is to go to the visual tree to find all Popup

objects and close them if they are open

I have VisualTreeHelpers on my blog that serve as an example of how you can navigate the visual tree, even though they are configured to only return the only object that meets the specified criteria, and not all objects.

You will probably need to tweak the code a little to make sure it returns all objects, but the code I am using to return 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 you can call it like this:

var popup = MyVisualTreeHelpers.FindChild<Popup>(MyWindow);

      

0


source







All Articles