我想要关闭一个托管WPF用户控件的窗体。在Windows应用程序中关闭当前窗体时使用类似于此的内容。但是对于WPF应用程序,我无法获取到用户控件父级的引用。
如何获取托管此控件的窗体,以便我可以关闭我的窗体?
this.Close()
如何获取托管此控件的窗体,以便我可以关闭我的窗体?
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;
}
之后,您可以使用WpfControl
的FormsWindow
属性来操作窗口。例如:
this.FormsWindow.Close();
我想补充一下@The_Smallest的非常清晰的答案。
如果您只是复制和粘贴事件处理程序代码,仍然需要将表单的ChildChanged事件设置为ElementHost_ChildChanged。我错过了这一步,花了30分钟来弄清楚为什么FormsWindow为空。
另一种解决方案可能是:
Window parent = Window.GetWindow(this);
parent.Close();
form.Close();
)。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;
}
}