Find all opened Popups in WPF application

痞子三分冷 提交于 2019-12-08 17:58:51

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/14479177/find-all-opened-popups-in-wpf-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!