35

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?

Alan Mendelevich
  • 3,591
  • 4
  • 32
  • 50

4 Answers4

90

This works for me:

Window parentWindow = Window.GetWindow(this);
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
CompG33k
  • 909
  • 6
  • 7
30
var parent = VisualTreeHelper.GetParent(this);
while (!(parent is Page))
{
    parent = VisualTreeHelper.GetParent(parent);
}
(parent as Page).DoStuff();
Community
  • 1
  • 1
Tomislav Markovski
  • 12,331
  • 7
  • 50
  • 72
  • Hi Tomislav Markovski, your solution is very helpful for finding the topmost parent i.e. Page. But the DoStuff() method could not be called. I get error saying 'Windows.UI.Xaml.Controls.Page' does not contain a definition for 'DoStuff' (are you missing a using directive or an assemply reference?) I desperately need to call a method in MainPage from a dynamic user control and unable to do this. Help please. – Merin Nakarmi Mar 12 '13 at 17:18
  • 3
    Change `while (!(parent is Page))` and `(parent as Page).DoStuff();` to test and cast to your page class. If that is MainPage, then `parent is MainPage` etc. Obviously `DoStuff()` should be the name of your function. – Tomislav Markovski Mar 13 '13 at 19:05
7

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
  • 286,951
  • 70
  • 623
  • 758
  • 3
    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 May 16 '09 at 07:20
0

i think best way is

var obj = VisualTreeHelper.GetParent((DependencyObject)Content);
  • 2
    This will only give you the direct parent. Consider if you have multiple nested user controls in one window. – ezolotko Aug 27 '13 at 06:38