How to close parent windows using WPF User Control

后端 未结 3 1225
失恋的感觉
失恋的感觉 2021-02-14 10:38

Assume that I have two WPF windows: window_One and window_Two.

  • window_One has one button. Clicking this button opens window_Two.
  • window_Two contains a Use
3条回答
  •  情书的邮戳
    2021-02-14 10:42

    Inside the custom control that you've created. You can access the parent window from within the button event click.

    Either by using the visual tree:

    var myWindow = (Window)VisualParent.GetSelfAndAncestors().FirstOrDefault(a => a is Window);
    myWindow.Close();
    

    or by simply:

    var myWindow = Window.GetWindow(this);
    myWindow.Close();
    

    Of course, the other option would be to create a custom event that says "MyButtonClicked" and then have the window that hosts the UserControl to listen to this event and when the Event is fired, you close the current window.

    Cheers!

提交回复
热议问题