WPF具有Popup类,可以在另一个窗口内打开(小型)窗口。例如,这可用于工具提示或组合框。
我需要查找当前在WPF窗口内打开的所有这些弹出窗口,以便我可以关闭它们。
如果有人仍需要:
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);
}
一种方法是通过遍历可视树来查找所有的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);