我有以下的标记两个问题:如何获取UIElement的父Popup?
<Popup>
<Button x:Name="button"/>
</Popup>
- 为什么
VisualTreeHelper.GetParent(button)
返回NULL? - 如何获得
UIElement
的父Popup
?
我有以下的标记两个问题:如何获取UIElement的父Popup?
<Popup>
<Button x:Name="button"/>
</Popup>
VisualTreeHelper.GetParent(button)
返回NULL?UIElement
的父Popup
?由于Button
正被显示在弹出时仅添加到视件树。
嗯... ...棘手
编辑
中有以下一种假设,即您的弹出窗口中的UserControl
的XAML定义,因此虽然它的子不得在可视树中弹出原始控件。
重复使用我之前发布的一些代码(我真的必须让我成为博客)。
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。但对于第二个this可能有所帮助。
zihotki的解决方案看起来很有前景(我还没有测试过)。
虽然VisualTreeHelper.GetParent(button)
返回null,您可以使用button.Parent
,它应该给你弹出对象。
@DaveClemmer:哇 - 是否有编辑问题和每一个答案的徽章? – RobSiklos 2013-08-21 16:14:27
而不是通过VisualTree
,你刚刚尝试了一段时间的循环,以走过元素的父母?
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
作为父母,但它为我工作。
确保PopUp
连接到VisualTree
。在“备注”部分查找更多信息 http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.popup(v=vs.95).aspx
即使打开的弹出窗口GetParent方法返回null – altso 2010-01-05 17:04:48
嗯......是的,这是真的,它位于显示在现有视觉效果之上的树顶部。因此偏移是相对于Silverlight控件本身。 – AnthonyWJones 2010-01-05 17:19:29