如何在 WPF 中获取顶部对象(窗口或页面)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/838825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a top object (Window or Page) in WPF?
提问by Alan Mendelevich
Within my custom WPF control I want to get a containing Window or Page. Window.GetWindow() method works fine when control is in a windowed app but when it's in the XBAP app in a browser it returns browser window instead of the page.
在我的自定义 WPF 控件中,我想获得一个包含窗口或页面。当控件位于窗口应用程序中时,Window.GetWindow() 方法工作正常,但当它位于浏览器中的 XBAP 应用程序中时,它返回浏览器窗口而不是页面。
Is there any other way to do this?
有没有其他方法可以做到这一点?
回答by CompG33k
This works for me:
这对我有用:
Window parentWindow = Window.GetWindow(this);
回答by Tomislav Markovski
var parent = VisualTreeHelper.GetParent(this);
while (!(parent is Page))
{
parent = VisualTreeHelper.GetParent(parent);
}
(parent as Page).DoStuff();
回答by Thomas Levesque
You can use the VisualTreeHelper class to retrieve the top-level control :
您可以使用 VisualTreeHelper 类来检索顶级控件:
DependencyObject GetTopLevelControl(DependencyObject control)
{
DependencyObject tmp = control;
DependencyObject parent = null;
while((tmp = VisualTreeHelper.GetParent(tmp)) != null)
{
parent = tmp;
}
return parent;
}
回答by user1497142
i think best way is
我认为最好的方法是
var obj = VisualTreeHelper.GetParent((DependencyObject)Content);