C# WinForm中使用WPF的控件

步骤1:创建WinForm工程

步骤2:在刚刚创建的WinForm工程中新建或者添加现有的WPF用户自定义控件

 
  1. <UserControl x:Class="wndFormTest.ComBoBoxButton"

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

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

  4. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

  5. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

  6. mc:Ignorable="d"

  7. d:DesignHeight="55" d:DesignWidth="200">

  8. <Grid>

  9. <ComboBox x:Name="_comBox" Foreground="Red" FontSize="24" Margin="0"></ComboBox>

  10. </Grid>

  11. </UserControl>

 
  1. public partial class ComBoBoxButton : UserControl

  2. {

  3. public ComBoBoxButton()

  4. {

  5. InitializeComponent();

  6.  
  7. // 添加测试数据

  8. for (int ix = 0; ix < 10; ix++)

  9. _comBox.Items.Add("abcdefg" + ix.ToString());

  10. }

  11. }

步骤3:添加相关引用


 

步骤4:在WinForm面板上添加ElementHost控件(工具箱中)
步骤5:在刚刚的ElementHost中的Child属性中添加刚刚生成的WPF控件(ElementHost是WPF控件的载体)

 
  1. public partial class Form1 : Form

  2. {

  3. private ElementHost _elemHost = new ElementHost(); // WPF载体

  4. private ComBoBoxButton _cbb = new ComBoBoxButton(); // WPF控件

  5. public Form1()

  6. {

  7. InitializeComponent();

  8.  
  9. _elemHost.Location = new Point(50, 50);

  10. _elemHost.Child = _cbb; // 绑定

  11. _elemHost.Width = 400;

  12. _elemHost.Height = 55;

  13.  
  14. this.Controls.Add(_elemHost);

  15. }

  16. }

步骤6:生成解决方案

步骤7:测试结果

猜你喜欢

转载自blog.csdn.net/bruce135lee/article/details/81111771