繁体   English   中英

如何从WPF用户控件中关闭托管WPF用户控件的窗体

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

我想关闭一个托管WPF用户控件的窗体。 在窗口应用程序中关闭当前表单时使用的类似这样的东西。 但对于WPF应用程序,我无法获得对用户控件parent的引用

如何获取托管此控件的Form,以便我可以关闭我的表单

this.Close()

添加到您的WpfControl属性

public Form FormsWindow { get; set; }

在你的WinForm中为ElementHost的事件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属性来操作窗口。 例:

this.FormsWindow.Close();

另一种解决方案可能是,

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

只想添加@The_Smallest的非常明确的答案。

如果您只是复制并通过事件处理程序代码,则仍需要将Forms的ChildChanged事件设置为ElementHost_ChildChanged。 我错过了这一步,花了30分钟试图找出为什么FormsWindow为null。

为了调用MyControl类的Form对象。 我们在其中有一个Form字段,我们传递一个实例对象open Form。 拥有一个指定的对象我们可以自由地操纵它(包括调用函数form.Close ();

WPF控件(使用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();
        }
    }
}

形成:

public class MainForm
{
    //...

    public Form form = null;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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