2

在我的 WPF 对象层次结构的深处,我创建了一个 Window 对象。

但是,我希望此窗口对象的所有者成为基础 Window 对象

我尝试使用以下类型的代码“爬上树”,但这种方法似乎不是最理想的:

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

如何访问基础 Window 对象?

我在想这样的事情:

伪代码:

Window baseWindow = this.BaseParent as Window;
4

2 回答 2

2

适用于所有类型的方法是沿着逻辑树向上走,直到找到所需类型的节点:

Window baseWindow = FindLogicalParent<Window>(this);

该方法在框架中不存在,所以这里有一个实现:

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;
}

具体来说Window,您可以使用:

Window.GetWindow(this);
于 2009-09-18T12:22:51.967 回答
0

请允许我回答这个问题:

Window baseWindow = Application.Current.Windows[0];
于 2009-09-18T12:04:27.247 回答