如何在WPF中调用Winform控件

如何在WPF中调用Winform控件,第1张

功能实现主要分三步:

1、添加两个引用:WindowsFormsIntegration.dll(负责整合WPF和Windows)、System.Windows.Forms.

2、在 XAML文件中添加两个誉指物引用(粗体部分):

<Window x:Class="CrossBowDemo.MainWindow"

xmlns:wfi ="clr-namespace:System.Windows.Forms.Integrationassembly=WindowsFormsIntegration"庆液

xmlns:wf ="clr-namespace:System.Windows.Formsassembly=System.Windows.Forms"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

title="Hosting Windows Forms Control In WPF"

Height="300"

Width="650"

ResizeMode="逗友NoResize"

Loaded="WindowLoadedHandler"

>

</Window>

3、在XAML编码区实现你想添加的控件

原文添加的是DataGridView控<wfi:WindowsFormsHost>

<wf:DataGridView x:Name="Dg" Dock="Fill" SelectionMode="FullRowSelect">

</wf:DataGridView>

</wfi:WindowsFormsHost>

当时把WPF的控件canvas的handle传给C++的项目去刷新图像的时候发现最后刷新的是整个WPF页面而不是控件所在的区域,还不知道有什么办法可以解决。

不过可以在WPF中嵌入WINFORM的图像控件PictureBox去做刷新。

嵌入方法:

1.在项目的References中加入WindowsFormsIntegration.dll和System.Windows.Form.dll

2.在败或页面的WPF中加入

[csharp] view plain copy

xmlns:wfi ="clr-namespace:System.Windows.Forms.Integrationassembly=WindowsFormsIntegration"

xmlns:wf ="clr-namespace:System.Windows.Formsassembly=System.Windows.Forms"

比如

[csharp] view plain copy

x:Class="WpfApplication1.MainWindow"

xmlns:wfi ="clr-namespace:System.Windows.Forms.Integrationassembly=WindowsFormsIntegration"

xmlns:wf ="clr-namespace:System.Windows.Formsassembly=System.Windows.Forms"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"首斗

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

title="MainWindow"察芹伍 Height="800" Width="1280" MouseMove="Window_MouseMove" MouseLeftButtonUp="Window_MouseLeftButtonUp" MouseDown="Window_MouseDown" MouseLeftButtonDown="Window_MouseLeftButtonDown">

然后我在Gridzhong 放下图像控件

[csharp] view plain copy

<Grid HorizontalAlignment="Left" Height="482" Margin="6,6,0,0" VerticalAlignment="Top" Width="737">

<wfi:WindowsFormsHost>

<wf:PictureBox x:Name="Cv_Main" Margin="0,0,0,0"></wf:PictureBox>

</wfi:WindowsFormsHost>

</Grid>

大功告成

在WinForm项目是无法直接转换WPF项目的,只能重新做。

但在WinForm中是可以使用WPF中的控件(或者由WPF创建的自定义控件)

1.新建一个winform项目;

2.在解决方案上新建一个wpf项目;

如图:

如果有如下错误,就在winform中的引用添加System.xaml的引用即可:

错误 1 类型“System.Windows.Markup.IComponentConnector”在未被引用的程序集中定义。必须添加对程序集“System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”的引用。

在winform中添加WPF项目下引用的三个程序集:PresentationCore,PrentationFramework,WindowsBase,以及wpf项目WpfApplication1的引用,如图:

在winform的Form1窗体的cs代码中添加using WpfApplication1的引用:

在winform中添加的button按钮的Click事件中New一下Wpf的窗体show出来即可显示:

private void button1_Click(object sender, EventArgs e)

{

WpfApplication1.MainWindow wpfwindow = new WpfApplication1.MainWindow()

wpfwindow.ShowDialog()

}

效果如图:


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11983798.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存