我要关闭承载WPF用户控件的窗口窗体。在窗口应用程序中关闭当前窗体时使用的类似内容。但对于WPF应用程序,我无法获得对用户控件父级的引用
如何获取承载此控件的窗体,以便关闭窗体
this.Close()
发布于 2010-12-04 02:32:22
添加到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();发布于 2012-11-07 22:47:13
另一种解决方案可以是,
Window parent = Window.GetWindow(this);
parent.Close();发布于 2014-12-20 06:18:54
我只想给@The_Smallest添加一个非常清晰的答案。
如果只是复制并传递事件处理程序代码,则仍然需要将窗体的ChildChanged事件设置为ElementHost_ChildChanged。我错过了这一步,花了30分钟试图弄清楚为什么FormsWindow是空的。
https://stackoverflow.com/questions/4348408
复制相似问题