Winform控件在WPF中使用的注意事项

从Winform转到WPF的时候,经常需要在WPF里面采用一些以前用Winform写过的控件。下面介绍在WPF中使用Winform的方法和注意事项。

1、在WPF中使用Winform的控件

(1)添加必须的dll。主要有:WindowsFormsIntegration.dll,System.Windows.Forms.dll

(2)在WPF中加入命名空间 

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

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

(3)加入控件

<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>

注意事项:

(1)有时候即使加入了上面的代码,有时候还是显示不了Winform控件。此时需要在Window加入属性AllowsTransparency="False"

(2)Winform控件后Wpf元素被Winform控件遮盖问题

考虑如果是因为渲染机制问题,始终将winform控件渲染在最上层的话,能不能将Wpf元素也使用WindowsFormsHost容器进行一层包裹呢?理论上应该是可以得,于是进行尝试,最外层使用WindosFormsHost,然后是Wpf元素的容器ElementHost,最后是我们需要的WPF界面元素:

<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wfi ="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
    <Grid>
        <wfi:WindowsFormsHost x:Name="mapContainer">
        </wfi:WindowsFormsHost>
        <wfi:WindowsFormsHost >
            <ElementHost>
                <StackPanel VerticalAlignment="Bottom" HorizontalAlignment="Right" Background="Blue" Width="75" Height="45">
                </StackPanel>
            </ElementHost>
        </wfi:WindowsFormsHost>
 
    </Grid>
</Window>

(3)WPF 忽略子控件事件触发父控件事件

IsHitTestVisible="False"

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值