WPF中如何将Rectangle置于WindowsFormsHost上方?已尝试Panel.ZIndex无效
问题解决:WPF中Rectangle被WindowsFormsHost遮挡的处理
问题根源
WindowsFormsHost是Win32原生窗口(HWND),而WPF的UI元素基于DirectComposition的软件渲染层。HWND窗口会默认显示在所有WPF元素的视觉上层,这是WPF与WinForms互操作的底层机制决定的——Panel.ZIndex仅对WPF元素之间的层级生效,无法改变HWND窗口与WPF元素的堆叠关系。
解决方案
方案1:用Popup承载Rectangle(快速适配现有代码)
将Rectangle放到Popup中,利用Popup独立HWND的特性,使其悬浮在WindowsFormsHost上方:
<Grid Grid.Column="1"> <StackPanel x:Name="drawPanel2" Orientation="Horizontal"> <WindowsFormsHost Background="Black" Height="720" x:Name="winforms_host" VerticalAlignment="Top" Width="540"/> </StackPanel> <Popup PlacementTarget="{Binding ElementName=winforms_host}" Placement="Top" IsOpen="True" AllowsTransparency="True"> <Rectangle Height="200" Width="540" Fill="AliceBlue"/> </Popup> </Grid>
AllowsTransparency="True"可以让Popup的透明区域生效,避免遮挡不需要的部分;PlacementTarget和Placement用于定位Popup到WindowsFormsHost的对应位置。
方案2:替换WindowsFormsHost为WPF原生Image控件(彻底解决层级问题)
如果你的图像流可以转换为WPF兼容的BitmapSource,直接用WPF的Image控件替代WindowsFormsHost,所有元素都属于WPF体系,此时Panel.ZIndex即可正常生效:
<Grid Grid.Column="1"> <StackPanel x:Name="drawPanel2" Orientation="Horizontal" Panel.ZIndex="0"> <Image x:Name="wpf_image" Background="Black" Height="720" VerticalAlignment="Top" Width="540"/> </StackPanel> <StackPanel x:Name="drawPanel" Orientation="Horizontal" Panel.ZIndex="1"> <Rectangle Height="200" Width="540" Fill="AliceBlue"/> </StackPanel> </Grid>
后台代码将图像流转换为BitmapSource的示例:
using (var stream = yourImageStream) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; bitmap.EndInit(); wpf_image.Source = bitmap; }
内容的提问来源于stack exchange,提问作者Marco Max
相关产品推荐
相关产品推荐

