参考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如下:
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代码为:
public MyWPFControl() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { MessageBox.Show(tbxInput.Text); }
4. 添加外部DLL库:windowsformsintegration, system.xaml
5. 修改Form1代码如下
using 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. 编译并且运行程序,效果图如下: