如何获得UIElement的父Popup? [英] How can I get the parent Popup for a UIElement?

查看:125
本文介绍了如何获得UIElement的父Popup?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有两个关于标记的问题:

I have two questions on markup below:

<Popup>
    <Button x:Name="button"/>
</Popup>

  1. 为什么VisualTreeHelper.GetParent(button)返回null?
  2. 如何为UIElement获取父级Popup?
  1. Why does VisualTreeHelper.GetParent(button) return null?
  2. How can I get the parent Popup for UIElement?

推荐答案

  1. 因为Button仅在显示弹出窗口时才添加到可视树中.

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆