【问题标题】:How to get an instance of hosting WinForm from a WPF user control?如何从 WPF 用户控件获取托管 WinForm 的实例?
【发布时间】:2018-07-20 09:38:48
【问题描述】:

我有一个 WPF UserControl,它托管在 WPF 窗口或 Windows 窗体 Form 中。当用户按下“X”按钮关闭托管窗口/表单时,我想抓住这个关闭事件并做一些操作。

为此,我订阅了 UserControl 的加载事件以获取托管窗口/表单实例并订阅其关闭事件。

它在 WPF 窗口中运行良好,但是当我尝试对 Form 执行相同操作时,我收到错误并且无法继续。

WPFUsercontrol.xaml.cs

private void WpfUsercontrol_OnLoaded(object sender, RoutedEventArgs e)
{
    Window window = Window.GetWindow(this);
    if (window != null)
        window.Closing += window_closing;

    Form form = this.Parent as Form;    
    //Error: Cannot convert from System.Windows.DependencyObject to System.Windows.Forms.Form    
}

如何实现关闭Form 的相同功能,就像我使用 WPF 窗口所做的那样?

【问题讨论】:

  • This 可能会对您有所帮助。

标签: c# wpf winforms formclosing


【解决方案1】:

您不能只将 WPF UserControl 的父级转换为 System.Windows.Forms.Form,即使该控件托管在 Windows 窗体 Form 中,因为托管并不是那么简单,需要额外的“黑魔法”。

相反,您必须先获取HwndSource 并获取其ElementHost 实例。有了它,您就可以访问TopLevelControl,这将是您正在寻找的Form

var hwndSource = (HwndSource)PresentationSource.FromDependencyObject(this);
var host = (ElementHost)Control.FromChildHandle(hwndSource.Handle);
Form form = (Form)host.TopLevelControl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 2011-11-12
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多