wPF VisualTreeHelper.GetParent returns wrong class?

Use this:

Popup oPopup = VisualHelper.GetLogicalParent<Popup>(oThumb);

...

public static T GetLogicalParent<T>(DependencyObject p_oElement)
    where T : DependencyObject
{
    DependencyObject oParent = p_oElement;
    Type oTargetType = typeof(T);
    do
    {
        oParent = LogicalTreeHelper.GetParent(oParent);
    }
    while (
        !(
            oParent == null
            || oParent.GetType() == oTargetType
            || oParent.GetType().IsSubclassOf(oTargetType)
        )
    );

    return oParent as T;
}

The content in a popup is added to a different visual tree with a parent which is the PopupRoot but you can use the logical tree helper to get the popup with this snippet :

LogicalTreeHelper.GetParent()

From MSDN :

When you add content to a Popup control, the Popup control becomes the logical parent to the content. Similarly, the Popup content is considered to be the logical child of the Popup. The child content is not added to the visual tree that contains the Popup control. Instead, the child content is rendered in a separate window that has its own visual tree when the IsOpen property is set to true.

++


LogicalTreeHelper is unable to reach the Popup as well the best one could do is try using the Name the "PopupRoot" to compare to GetType().Name.


Try walking the Logical tree and not the Visual tree

LogicalTreeHelper.GetParent()

Tags:

Wpf