题
深我的WPF对象内部的 hiearchy 强>我创建窗口对象。
但是,我想此窗口对象的所有者以被的基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;
解决方案
这是对所有类型的工程分析,直到你找到所需要的类型的节点走了逻辑树:
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);
其他提示
允许我来回答这个之一:
Window baseWindow = Application.Current.Windows[0];
不隶属于 StackOverflow