如何获得UIElement的父Popup? [英] How can I get the parent Popup for a UIElement?
问题描述
我在下面有两个关于标记的问题:
I have two questions on markup below:
<Popup>
<Button x:Name="button"/>
</Popup>
- 为什么
VisualTreeHelper.GetParent(button)
返回null? - 如何为
UIElement
获取父级Popup
?
- Why does
VisualTreeHelper.GetParent(button)
return null? - How can I get the parent
Popup
forUIElement
?
推荐答案
-
因为
Button
仅在显示弹出窗口时才添加到可视树中.
Because the
Button
is only added to the visual tree when the popup is being displayed.
嗯...很棘手...
Hmm... tricky ...
修改
在下面的假设中,您的弹出窗口是在UserControl
的XAML中定义的,因此尽管其子级可能不在可视树中,但弹出基元控件是.
There is an assumption in the following that your popup is defined in the XAML of UserControl
so whilst its child may not be in the visual tree the popup primitive control is.
重新使用我之前发布的一些代码(我真的必须给我写博客).
Re-using some code I've posted before (I really must get me a blog).
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
统一对添加在可视树中的对象的搜索.因此,在后面的用户控件代码中,您可以执行以下操作:-
This adds an extension method to the DependencyObject
which uses the VisualTreeHelper
to unify the search for objects added in the visual tree. So in the usercontrol code behind you can do this:-
var popup this.Descendents()
.OfType<Popup>()
.Where(p => p.Child == button)
.FirstOrDefault();
这将找到Popup
,它是按钮"的父级.
This will find the Popup
which is the parent of "button".
这篇关于如何获得UIElement的父Popup?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!