WPF User Control Parent

后端 未结 17 1111
不知归路
不知归路 2020-11-28 02:18

I have a user control that I load into a MainWindow at runtime. I cannot get a handle on the containing window from the UserControl.

I hav

17条回答
  •  日久生厌
    2020-11-28 02:44

    Try using the following:

    Window parentWindow = Window.GetWindow(userControlReference);
    

    The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

    You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

    this.Loaded += new RoutedEventHandler(UserControl_Loaded); 
    

提交回复
热议问题