WinForm 与 WPF 之间控件使用

在WPF中使用WinForm控件方法

1、      首先添加对如下两个dll文件的引用:WindowsFormsIntegration.dll,System.Windows.Forms.dll。

 

2、      在要使用WinForm控件的WPF窗体的XAML文件中添加如下内容:

 

xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"

xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"

 

3、       在WPF的容器控件内如StackPanel内首先要添加WinForm控件的宿主容器,用于衔接WPF和WinForm.

 

对应XAML如下:

    <StackPanel>

            <wfi:WindowsFormsHost>

                <wf:Label x:Name="wfLabel" Text="winForm控件在此" />

            </wfi:WindowsFormsHost>

            <wfi:WindowsFormsHost>

                <wf:Button x:Name="wfButton" Text="确定" Click="wfButton_Click" />

            </wfi:WindowsFormsHost>

            <Button Content="Button" Margin="10" Name="button1"/>

        </StackPanel>

 

4、       如果要在WPF后台代码中访问上面的Lable,可直接像在WinForm中使用一样。如在点击某一按钮时改变Lable内容,代码如下:wpfLabel.Text=”内容已改变”;

 

 

在WinForm中使用WPF控件方法

 

1、      首先添加对WPF所需的程序集,

PresentationCore
PresentationFramework
system.Xaml
WindowsBase
WindowsFormsIntegration

2、 在项目中新建一个用户控件(WPF)或引用一个用户控件(WPF).

<UserControl x:Class="WindowsFormsApp1.UserControl1">
   <Grid>
    <hc:ComboBox x:Name="_comBox" >
      <CheckBox Content="test">
    </hc:ComboBox>
  <Grid>
</UserControl>

3、      重新生成项目,将 工具箱自动生成的WPF 控件拖入Winform中

 ElementHost 选择所承载的内容:UserControl1

3、 在WinForm后台代码可修改对应的WPF控件.

 ((UserControl1)elementHost2.Child)._combox.Items.Add(new HandyControl.Controls.ComboBox());

4、 Demo效果

 下拉框里新增加了一个ComboBox

posted @ 2023-08-03 22:11  嗷大猫  阅读(671)  评论(0)    收藏  举报