tags:

views:

63

answers:

2

Deep inside my WPF object hiearchy I create a Window object.

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

I've tried "climbing up 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 base Window object?

I'm thinking of something like this:

PSEUDO-CODE:

Window baseWindow = this.BaseParent as Window;
A: 

Allow me to answer this one:

Window baseWindow = Application.Current.Windows[0];
Edward Tanguay
This assumes you only have one window.
Drew Noakes
+2  A: 

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

Window baseWindow = FindLogicalParent<Window>(this);

That method doesn't exist in the framework, so here's an 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);
Drew Noakes