在WPF应用程序中查找所有打开的弹出窗口

10

WPF具有Popup类,可以在另一个窗口内打开(小型)窗口。例如,这可用于工具提示或组合框。

我需要查找当前在WPF窗口内打开的所有这些弹出窗口,以便我可以关闭它们。


可能是从代码中强制关闭所有打开的弹出窗口的重复问题。 - Lukazoid
2个回答

22

如果有人仍需要:

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

0

一种方法是通过遍历可视树来查找所有的Popup对象,并在它们打开时关闭它们。

我在我的博客上有一些VisualTreeHelpers,提供了一个如何遍历可视树的示例,尽管它们设置为仅返回与指定条件匹配的单个对象,而不是所有对象。

您可能需要修改代码以确保它返回所有对象,但我用于返回单个对象的代码如下:

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

可以这样调用:

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

4
你确定这适用于弹出窗口吗?我不确定,因为我认为弹出窗口是Win32窗口,而不是实际的可视化树的一部分。 - HerrLoesch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接