How to close a window form that hosts a WPF user control from a WPF user control

I want to close the window form that hosts the WPF user control. Something like this is used when closing the current form in the application window. But for a WPF application, I cannot get a link to the parent user controls

How to get the form in which this control is placed so that I can close my form

this.Close ()

+3
source share
3 answers

Add to the WpfControl Property

public Form FormsWindow { get; set; }

In your WinForm add an event handler for ElementHostevent ChildChanged:

using System.Windows.Forms.Integration; 

public MyForm() {
    InitializeComponent();
    elementHost.ChildChanged += ElementHost_ChildChanged;
}
void ElementHost_ChildChanged(object sender, ChildChangedEventArgs e) {
    var ctr = (elementHost.Child as UserControl1);
    if (ctr != null)
        ctr.FormsWindow = this;
}

FormsWindow WpfControl . :

this.FormsWindow.Close();
+9

,

 Window parent = Window.GetWindow(this);
 parent.Close();
+1

I just want to add a very clear answer to @The_Smallest otherwise.

If you just copy and skip the event handler code, you still need to set the Forms ChildChanged event to ElementHost_ChildChanged. I skipped this step and spent 30 minutes trying to figure out why FormsWindow was null.

+1
source

Source: https://habr.com/ru/post/1778369/


All Articles