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

4
我想要关闭一个托管WPF用户控件的窗体。在Windows应用程序中关闭当前窗体时使用类似于此的内容。但是对于WPF应用程序,我无法获取到用户控件父级的引用。
如何获取托管此控件的窗体,以便我可以关闭我的窗体?
this.Close()
4个回答

13

将此添加到您的 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;
}

之后,您可以使用WpfControlFormsWindow属性来操作窗口。例如:

this.FormsWindow.Close();

非常感谢,这是正确的,但似乎我们必须在 InitializeComponent(); 之后设置子项。 - MSH

1

我想补充一下@The_Smallest的非常清晰的答案。

如果您只是复制和粘贴事件处理程序代码,仍然需要将表单的ChildChanged事件设置为ElementHost_ChildChanged。我错过了这一步,花了30分钟来弄清楚为什么FormsWindow为空。


1

另一种解决方案可能是:

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

4
如果WPF用户控件嵌套在Windows Forms中,它将无法正常工作。 - Zyo

0
为了调用已经存在的MyControl类的Form对象,我们在其中有一个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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接