WPF中使用winform 控件

来源:互联网 发布:网络上bgm是什么意思 编辑:程序博客网 时间:2024/05/18 03:54

原来有一个WINFORM项目的功能模块希望集成到新的WPF项目中,怎样集成才最简单?

    思路:将原来的WINFORM项目类型改为WindowsFormsControlLibrary类型就OK了。

步骤:

   1、所以我们就直接建立一个WindowsFormsControlLibrary项目吧!接着我在该项目中新增Windows Form,为Form1。也就是将原来的项目类型改造为WindowsFormsControlLibrary项目。

    




2新建Wpf项目

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

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

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:WinFormHost="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        Title="MainWindow" Height="350" Width="525">

(3)添加HOST宿主

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:WinFormHost="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
           
        </Grid.ColumnDefinitions>
        <WindowsFormsHost Name="windowsFormsHost1" Grid.Column="0" Margin="3"></WindowsFormsHost>
    </Grid>
   
</Window>

windowsFormsHost1 就是FORM窗体显示的宿主

(4)接着我们要在WPF项目中引用刚才WindowsFormsControlLibrary项目建出来的dll档

(5)在MainWindow.xaml.cs中添加代码

 

using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WindowsFormsControlLibrary1;
using System.Windows.Forms;


namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Form1 _form1 = new Form1();
        public MainWindow()
        {
            InitializeComponent();
            _form1.TopLevel  = false;
            _form1.FormBorderStyle = FormBorderStyle.None;
            windowsFormsHost1.Child = _form1;


        }
    }
}

0 0
原创粉丝点击