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

Sha*_*pta 4 c# wpf winforms

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

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

this.Close()

The*_*est 12

添加到您的WpfControl属性

public Form FormsWindow { get; set; }
Run Code Online (Sandbox Code Playgroud)

在你的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;
}
Run Code Online (Sandbox Code Playgroud)

之后,您可以使用FormsWindowWpfControl 的属性来操作窗口.例:

this.FormsWindow.Close();
Run Code Online (Sandbox Code Playgroud)