在WPF应用程序中查找所有打开的弹出窗口
WPF有一个Popup类,您可以使用它在另一个窗口中打开一个(小)窗口。例如,这用于工具提示或组合框在WPF应用程序中查找所有打开的弹出窗口,wpf,popup,Wpf,Popup,WPF有一个Popup类,您可以使用它在另一个窗口中打开一个(小)窗口。例如,这用于工具提示或组合框 我需要找到当前在WPF窗口中打开的所有弹出窗口,以便关闭它们 一种方法是导航视觉树,找到所有弹出窗口对象,并在它们打开时关闭它们 我有一些示例提供了如何导航可视化树的示例,尽管它们被设置为只返回一个符合指定条件的对象,而不是所有对象 您可能需要稍微修改代码以确保它返回所有对象,但我用于返回单个对象的代码如下所示: /// <summary> /// Looks for
我需要找到当前在WPF窗口中打开的所有弹出窗口,以便关闭它们 一种方法是导航视觉树,找到所有
弹出窗口
对象,并在它们打开时关闭它们
我有一些示例提供了如何导航可视化树的示例,尽管它们被设置为只返回一个符合指定条件的对象,而不是所有对象
您可能需要稍微修改代码以确保它返回所有对象,但我用于返回单个对象的代码如下所示:
/// <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);
//
///按类型查找父控件中的子控件
///
公共静态T FindChild(DependencyObject父对象)
其中T:DependencyObject
{
//确认父项有效。
if(parent==null)返回null;
T foundChild=null;
int childrenCount=visualtreeheloper.GetChildrenCount(父级);
for(int i=0;i
可以这样称呼:
/// <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);
var popup=MyVisualTreeHelpers.FindChild(MyWindow);
如果有人仍然需要:
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);
}
公共静态IEnumerable GetOpenPopups()
{
返回PresentationSource.CurrentSources.OfType()
.选择(h=>h.RootVisual)
第()类
.选择(f=>f.Parent)
第()类
.式中(p=>p.IsOpen);
}
的可能重复项您确定这适用于弹出窗口吗?我不确定,因为我认为弹出窗口是Win32 windows,而不是可视树的实际部分。