在WPF中添加Windows Form控件(包括 ocx控件)

 

首先,需要向项目中的reference添加两个dll,一个是.NET库中的System.Windows.Forms,另外一个是WindowsFormsIntegration,它的位置一般是在C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF 里。

添加完两个dll以后,就可以在控件库中找到WindowsFormsHost这个控件了。这个控件是我们添加Windows Form控件的基础。跟别的其他的控件一样,它也是可控的,可以自定义它在窗口中的位置、控件大小颜色等属性。我一般是比较喜欢在Blend里面创建控件。可以在Blend中的Assets中找到这个控件。或者你也可以在vs中的设计模式下的toolbox中找到它。放置完以后在xmal代码中会自动生成相应代码:

<WindowsFormsHost Height="196" HorizontalAlignment="Left" Margin="104,65,0,0" Name="windowsFormsHost1" VerticalAlignment="Top" Width="286"/>

然后,需要在xmal的开始处添加两行代码

xmlns:WinFormHost="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:WinFormControls="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

这样就可以在WindowsFormsHost下放置需要的Windows Form控件了,比如

<WindowsFormsHost Height="196" HorizontalAlignment="Left" Margin="104,65,0,0" Name="windowsFormsHost1" VerticalAlignment="Top" Width="286">
<WinFormControls:Button Text="WinformButton" Width="150"/>
</WindowsFormsHost>

这是最简单的情况,就是添加了一个button,运行以后会发现整个WindowsFormsHost上就放置了一个硕大的button……如果需要有布局的可以在WindowsFormsHost下放置Panel等布局控件。

最后附上整个xmal代码

复制代码
复制代码
<Window x:Class="WpfApplication2.MainWindow"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WinFormHost
="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:WinFormControls
="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title
="MainWindow" Height="350" Width="525">
<Grid>
<WindowsFormsHost Height="196" HorizontalAlignment="Left" Margin="104,65,0,0" Name="windowsFormsHost1" VerticalAlignment="Top" Width="286">
<WinFormControls:Button Text="WinformButton" Width="150"/>
</WindowsFormsHost>
</Grid>
</Window>
复制代码
复制代码

附上一个有用的链接,如果想做响应的朋友可以参考一下

http://www.dotblogs.com.tw/ouch1978/archive/2011/01/03/wpf_windowsformsintegration.aspx

posted @   长白山  阅读(1795)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
点击右上角即可分享
微信分享提示