开发者

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

th开发者_如何学Gois.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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜