參考http://keyvan.io/host-wpf-controls-in-windows-forms
在windows form appliation中添加wpf空間,需要使用一個ElementHost的容器,接着將創建出來的WPF對象賦值到ElementHost的child屬性中,類似子控件添加到Panel或者Form的controls容器中,可以ElementHost只能對應一個wpf控件,接着將ElementHost添加到父級Controls中。
實現如下:
1. 創建Windows Form Application項目,命名為HostWPFWinForm
2. 接着添加新建項為“用戶控件(WPF)”,命名為MyWPFControl
3. 給剛生成的WPF控件添加lable, textbox 與button,對應的XAML如下:

Code<UserControl x:Class="HostWPFWinForm.MyWPFControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Height="37.5" Width="268">
<Grid Margin="0,0,0,200">
<Label x:Name="lblInput" Content="Input:" HorizontalAlignment="Left" Height="26" Margin="12,8,0,-34" VerticalAlignment="Top" Width="48"/>
<TextBox x:Name="tbxInput" HorizontalAlignment="Left" Height="21" Margin="60,12,0,-33" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"/>
<Button Content="Click" HorizontalAlignment="Left" Height="21" Margin="185,13,0,-34" VerticalAlignment="Top" Width="76" Click="Button_Click"/>
</Grid>
</UserControl>
對應的CS代碼為:

Code public MyWPFControl()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(tbxInput.Text);
}
4. 添加外部DLL庫:windowsformsintegration, system.xaml
5. 修改Form1代碼如下

Codeusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
namespace HostWPFWinForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Add WPF Control
MyWPFControl control = new MyWPFControl();
ElementHost host = new ElementHost();
host.Top = 0;
host.Left = 0;
host.Width = 300;
host.Height = 40;
host.Child = control;
this.Controls.Add(host);
}
}
}
6. 編譯並且運行程序,效果圖如下: