如何在WPF网格或Viewbox中显示WinForms窗口

时间:2016-11-10 20:00:33

标签: c# wpf winforms

在xml文件中:

<Viewbox name="viewbox1"></Viewbox>

在C#代码隐藏中:

windowformClass window1 = new windowformClass(); // this is the WinForms object, not WPF
viewbox1.Child = window1;

当我将window1分配给viewbox1时,它会显示一个错误,该错误无法将窗体转换为System.Window.ElementUI

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

你应该使用WPF的WinForms互操作主机控件,称为WindowsFormsHost 以下代码是从MSDN

中提取和改编的
// Create the interop host control.
System.Windows.Forms.Integration.WindowsFormsHost host =
    new System.Windows.Forms.Integration.WindowsFormsHost();

// Create your control.
windowformClass window1 = new windowformClass();

// Assign the control as the host control's child.
host.Child = window1;

// Set the interop host control as the ViewBox child.
viewbox1.Child = host;

A user reported a problem with hosting the WindowsFormHost inside a ViewBox。你应该检查一下,以防你遇到问题。

由于你(显然)是新人,我想给你一点提示: MSDN和SO上有很多关于这个主题的资源,可以通过您最喜欢的搜索引擎上的简单搜索找到 下一次,在发布问题之前尝试找到解决方案,以便仅保留关于主题的最佳答案,并将主持人关闭问题的工作保存为副本。
有关详情,请查看help from SO