How can you get the parent of a UIElement?

14,554

Well, if you need to find a logical parent you can just use LogicalTreeHelper in the same manner as VisualTreeHelper.

As for "...and have any thoughts why they didn't just define a Parent property there instead of on FrameworkElement?". Basically, the notion of "Logical Tree" is introduced on the FrameworkElement level. See http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.aspx (see Remarks) for details of what FrameworkElement adds to UIElement. Here is what it says about Logical Trees:

The logical tree: The general WPF programming model is often expressed in terms of being a tree of elements. Support for expressing the tree of elements as a logical tree, and accompanying support for defining that tree in markup is implemented at the FrameworkElement level. Note however that FrameworkElement deliberately does not define a content model, and leaves that responsibility to derived classes. For more information, see Trees in WPF.

Share:
14,554
Mark A. Donohoe
Author by

Mark A. Donohoe

Large Developer at Large!

Updated on June 08, 2022

Comments

  • Mark A. Donohoe
    Mark A. Donohoe almost 2 years

    Ok, I know that FrameworkElement, which is a direct subclass of UIElement, has a Parent property, but Panels have children of type UIElement, not FrameworkElement (Children is of type UIElementCollection) which seems it would mean you can add UIElements directly to a Panel.

    That said, if you have a UIElement and want to see if it has a parent that's a panel, the only way I know how to test this is with the VisualTreeHelper, but that's the visual tree, not the logical tree. (At least we know a Panel doesn't have a template so maybe that's the way, but still...)

    So asides from the VisualTreeHelper, does anyone know how to know which panel is the parent of a UIElement? (...and have any thoughts why they didn't just define a Parent property there instead of on FrameworkElement?)

    Thanks!

  • Mark A. Donohoe
    Mark A. Donohoe about 13 years
    I know the diff. between the physical tree and the logical tree. That's not what I asked. Nor can I use the LogicalTreeHelper here as the canvas may very well be part of the Visual Tree. I do however see your point about the parent. My argument there would be why not create separate VisualParent too then? Guess what it comes down to is I have no choice but to use the VisualTreeHelper (and maybe an attached method for convenience) to get the parent panel. And even though technically it's not the answer, I'm marking it as such anyway because it doesn't look like there is one.