简体   繁体   中英

how to close window form which is hosting WPF user control from within a WPF user control

I want to close a window form that is hosting a WPF user control. Something like this as used while closing a current form in window application. But for WPF application I am not able to get reference to user controls parent

How to get Form which is hosting this control so that I can close my form

this.Close()

Add to your WpfControl property

public Form FormsWindow { get; set; }

In your WinForm add event handler for ElementHost 's event 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;
}

After that you can use the FormsWindow property of your WpfControl to manipulate window. Example:

this.FormsWindow.Close();

An alternative solution could be,

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

Just want to add to @The_Smallest's otherwise very clear answer.

If you just copy and past the event handler code, you will still need to set your Forms's ChildChanged event to ElementHost_ChildChanged. I missed that step and spent 30 minutes trying to figure out why FormsWindow was null.

In order to call the Form object of the MyControl class already. We have in it a Form field to which we pass an instance object open Form. Having an assigned object we can freely manipulate it (including also call the function form.Close ();

WPF Control (with XAML):

public class MyControl : UserControl
{
    public Form form = null;

    public MyControl()
    {
        InitializeComponent();

        this.PreviewKeyDown += new KeyEventHandler(HandleEsc);
    }

    private void HandleEsc(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Escape)
        {
            form.Close();
        }
    }
}

Form:

public class MainForm
{
    //...

    public Form form = null;

    public MainForm(MyControl myControl)
    {
        InitializeComponent();
        //...
        myControl.form = (Form)this;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM