How can I access the underlying parent in the WPF hierarchy?

Inside my WPF hiearchy object, I create a Window object.

However, I want the owner of this window object to be the underlying Window object .

I have tried climbing the tree with the following type of code, but this approach seems suboptimal :

(((((((TabGroupPane)((ContentPane) this.Parent).Parent).Parent as
SplitPane).Parent as DocumentContentHost).Parent as 
XamDockManager).Parent as ContentControl).Parent as 
StackPanel).Parent...

      

How can I access the underlying Window object?

I am thinking of something like this:

pseudocode:

Window baseWindow = this.BaseParent as Window;

      

+2


source to share


2 answers


An approach that works for all types is to walk up the logical tree until it finds a node of the required type:

Window baseWindow = FindLogicalParent<Window>(this);

      

This method doesn't exist in the framework, so here's the implementation:

internal static T FindLogicalParent<T>(DependencyObject obj)
   where T : DependencyObject
{
    DependencyObject parent = obj;
    while (parent != null)
    {
        T correctlyTyped = parent as T;
        if (correctlyTyped != null)
            return correctlyTyped;
        parent = LogicalTreeHelper.GetParent(parent);
    }

    return null;
}

      




For Window

specifically, you can use:

Window.GetWindow(this);

      

+2


source


Let me answer this question:



Window baseWindow = Application.Current.Windows[0];

      

0


source







All Articles