【问题标题】:Find all opened Popups in WPF application在 WPF 应用程序中查找所有打开的弹出窗口
【发布时间】:2013-01-23 11:58:00
【问题描述】:

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

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

【问题讨论】:

标签: wpf popup


【解决方案1】:

如果有人还需要:

  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】:

    这样做的一种方法是导航可视树以查找所有Popup 对象,如果它们打开则关闭它们

    我有一些VisualTreeHelpers on my blog 提供了如何导航可视树的示例,尽管它们被设置为仅返回与指定条件匹配的单个对象,而不是所有对象。

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

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

    【讨论】:

    • 您确定这适用于弹出窗口吗?我不确定,因为我认为弹出窗口是 Win32 窗口,而不是可视化树的实际部分。
    猜你喜欢
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多