WPF中使用winform 控件

原來有一個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;


        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章