How can I access the base parent of an object in a WPF hierarchy?
Question
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;
Solution
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);
OTHER TIPS
Allow me to answer this one:
Window baseWindow = Application.Current.Windows[0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow