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"

猜你喜欢

转载自blog.csdn.net/woddle/article/details/81182188