Search code examples
silverlightpopupuielement

How can I get the parent Popup for a UIElement?


I have two questions on markup below:

<Popup>
    <Button x:Name="button"/>
</Popup>
  1. Why does VisualTreeHelper.GetParent(button) return null?
  2. How can I get the parent Popup for UIElement?

Solution

    1. Because the Button is only added to the visual tree when the popup is being displayed.

    2. Hmm... tricky ...

    Edit

    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;
            }
        }
    }
    

    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();
    

    This will find the Popup which is the parent of "button".