我想关闭托管WPF用户控件的窗体。在窗口应用程序中关闭当前表单时使用的类似这样的东西。但是对于WPF应用程序,我无法引用用户控件parent
如何获取托管此控件的Form,以便我可以关闭我的表单
this.Close()
答案 0 :(得分:12)
添加到您的WpfControl属性
public Form FormsWindow { get; set; }
在ElementHost
的事件ChildChanged
的WinForm添加事件处理程序中:
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();
答案 1 :(得分:1)
另一种解决方案可能是,
Window parent = Window.GetWindow(this);
parent.Close();
答案 2 :(得分:1)
只想添加@The_Smallest,否则非常明确的答案。
如果您只是复制并浏览事件处理程序代码,则仍需要将Forms的ChildChanged事件设置为ElementHost_ChildChanged。我错过了那一步,花了30分钟试图找出为什么FormsWindow为空。
答案 3 :(得分:0)
为了已经调用MyControl类的Form对象。我们在其中有一个Form字段,我们将实例对象打开的Form传递给该Form字段。有了分配的对象,我们可以自由地对其进行操作(包括调用函数<input type="text" name="hu_detail[0][reference_id]" value="abc">
<input type="text" name="hu_detail[0][qty]" value="12">
WPF控件(带有XAML):
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();
}
}
}