1、 首先添加對如下兩個dll文件的引用:WindowsFormsIntegration.dll,System.Windows.Forms.dll。
2、 在要使用WinForm控件的WPF窗體的XAML文件中添加如下內容:
即:
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
3、 在WPF的容器控件內如StackPanel內首先要添加WinForm控件的宿主容器,用於銜接WPF和WinForm,
對應XAML如下:
<StackPanel> <wfi:WindowsFormsHost> <wf:Label x:Name="wfLabel" Text="winForm控件在此" /> </wfi:WindowsFormsHost> <wfi:WindowsFormsHost> <wf:Button x:Name="wfButton" Text="確定" Click="wfButton_Click" /> </wfi:WindowsFormsHost> <Button Content="Button" Margin="10" Name="button1"/> </StackPanel>
說明:<wfi:WindowsFormsHost></wfi:WindowsFormsHost>即為WinForm控件的宿主容器,每一個宿主容器只能放一個WinForm控件,如下例,放了三個WinForm控件,分別放在三個宿主容器里面,該容器可以設置屬性來調整大小和布局。
注意:如上我添加的WinForm控件如在指定其Name時,必須加前綴x:,如添加Lable時<wf:Label x:Name="wpfLabel" Text="我是WPF中的WinForm控件” />,否則后台代碼無法訪問。
4、 如果要在WPF后台代碼中訪問上面的Lable,可直接像在WinForm中使用一樣。如在點擊某一按鈕時改變Lable內容,代碼如下:wpfLabel.Text=”內容已改變”;
5、 以使用WinForm控件wpfLabel改變標記為例,說明后台用法:
完整后台代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace ChangeDetection { /// <summary> /// Window4.xaml 的交互邏輯 /// </summary> public partial class Window4 : Window { public Window4() { InitializeComponent(); } private void wfButton_Click(object sender, EventArgs e) { wfLabel.Text= "內容已改變"; } } }
完整XAML如下:
<Window x:Class="ChangeDetection.Window4" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:ChangeDetection" xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" mc:Ignorable="d" Title="Window4" Height="300" Width="300"> <StackPanel> <wfi:WindowsFormsHost> <wf:Label x:Name="wfLabel" Text="winForm控件在此" /> </wfi:WindowsFormsHost> <wfi:WindowsFormsHost> <wf:Button x:Name="wfButton" Text="確定" Click="wfButton_Click" /> </wfi:WindowsFormsHost> <Button Content="Button" Margin="10" Name="button1"/> </StackPanel> </Window>
