3

我对以下标记有两个问题:

<Popup>
    <Button x:Name="button"/>
</Popup>
  1. 为什么VisualTreeHelper.GetParent(button)返回null?
  2. 我怎样才能得到Popup父母UIElement
4

5 回答 5

5

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父母的东西上测试过它,但它对我有用。

于 2010-10-05T10:17:06.187 回答
3
  1. 因为Button仅在显示弹出窗口时才将其添加到可视树中。

  2. 嗯……棘手……

编辑

以下假设您的弹出窗口是在 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哪个是“按钮”的父级。

于 2010-01-05T16:57:38.027 回答
2

Popup控制有时很烦人。而且我现在不知道为什么VisualTreeHelper.GetParent(button)返回null。但对于第二个,可能会有所帮助。

于 2010-01-05T17:32:36.310 回答
1

zihotki 的解决方案看起来很有希望(我还没有测试过)。

虽然VisualTreeHelper.GetParent(button)返回 null,但您可以使用button.Parent,它应该为您提供弹出对象。

于 2010-02-10T14:19:55.297 回答
0

确保PopUp连接到VisualTree. 在备注部分找到更多信息 http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.popup(v=vs.95).aspx

于 2012-11-27T16:38:16.370 回答