views:

939

answers:

2

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?

+2  A: 

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;
}
Thomas Levesque
Hmm... I think I've already posted this comment... This doesn't work when your control is in a Template. The loop ends when you reach the template "root".
Alan Mendelevich
A: 
var parent = VisualTreeHelper.GetParent(this);
        while (!(parent is Page))
        {
            parent = VisualTreeHelper.GetParent(parent);
        }
        (parent as Page).DoStuff();
Tomislav Markovski