Winform控制元件在WPF中使用的注意事項
阿新 • • 發佈:2018-12-31
從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"