How to get a top object (Window or Page) in WPF? [

2019-02-03 01:54发布

This question already has an answer here:

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.

Is there any other way to do this?

4条回答
Explosion°爆炸
2楼-- · 2019-02-03 02:41
var parent = VisualTreeHelper.GetParent(this);
while (!(parent is Page))
{
    parent = VisualTreeHelper.GetParent(parent);
}
(parent as Page).DoStuff();
查看更多
淡お忘
3楼-- · 2019-02-03 02:42

This works for me:

Window parentWindow = Window.GetWindow(this);
查看更多
家丑人穷心不美
4楼-- · 2019-02-03 02:44

You can use the VisualTreeHelper class to retrieve the top-level control :

DependencyObject GetTopLevelControl(DependencyObject control)
{
    DependencyObject tmp = control;
    DependencyObject parent = null;
    while((tmp = VisualTreeHelper.GetParent(tmp)) != null)
    {
        parent = tmp;
    }
    return parent;
}
查看更多
甜甜的少女心
5楼-- · 2019-02-03 02:50

i think best way is

var obj = VisualTreeHelper.GetParent((DependencyObject)Content);
查看更多
登录 后发表回答