WPF User Control Parent

后端 未结 17 1125
不知归路
不知归路 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:49

    I needed to use the Window.GetWindow(this) method within Loaded event handler. In other words, I used both Ian Oakes' answer in combination with Alex's answer to get a user control's parent.

    public MainView()
    {
        InitializeComponent();
    
        this.Loaded += new RoutedEventHandler(MainView_Loaded);
    }
    
    void MainView_Loaded(object sender, RoutedEventArgs e)
    {
        Window parentWindow = Window.GetWindow(this);
    
        ...
    }
    

提交回复
热议问题