我对以下标记有两个问题:
<Popup>
<Button x:Name="button"/>
</Popup>
- 为什么
VisualTreeHelper.GetParent(button)
返回null? - 我怎样才能得到
Popup
父母UIElement
?
我对以下标记有两个问题:
<Popup>
<Button x:Name="button"/>
</Popup>
VisualTreeHelper.GetParent(button)
返回null?Popup
父母UIElement
?VisualTree
您是否只是尝试了一个 while 循环来遍历元素的 .Parents 而不是通过.Parents ?
private void TryClosePopupParent(object o)
{
while (o != null)
{
Popup p = (o as Popup);
if(p == null)
{
o = (o as FrameworkElement).Parent;
}
else
{
p.IsOpen = false;
break;
}
}
}
我从来没有在没有作为PopUp
父母的东西上测试过它,但它对我有用。
因为Button
仅在显示弹出窗口时才将其添加到可视树中。
嗯……棘手……
编辑
以下假设您的弹出窗口是在 XAML 中定义的,UserControl
因此其子项可能不在弹出窗口原语控件所在的可视树中。
重新使用我之前发布的一些代码(我真的必须给我一个博客)。
public static class VisualTreeEnumeration
{
public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
{
int count = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(root, i);
yield return child;
foreach (var descendent in Descendents(child))
yield return descendent;
}
}
}
这增加了一个扩展方法,DependencyObject
它使用VisualTreeHelper
来统一搜索添加到可视树中的对象。所以在后面的用户控件代码中你可以这样做: -
var popup this.Descendents()
.OfType<Popup>()
.Where(p => p.Child == button)
.FirstOrDefault();
这将找到Popup
哪个是“按钮”的父级。
Popup
控制有时很烦人。而且我现在不知道为什么VisualTreeHelper.GetParent(button)
返回null。但对于第二个,这可能会有所帮助。
zihotki 的解决方案看起来很有希望(我还没有测试过)。
虽然VisualTreeHelper.GetParent(button)
返回 null,但您可以使用button.Parent
,它应该为您提供弹出对象。
确保PopUp
连接到VisualTree
. 在备注部分找到更多信息
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.popup(v=vs.95).aspx