c# WPF transparency over Winform controls

2020-06-03 07:30发布

问题:

I have a WPF control that I would like to overlay onto a WinForms application. So I have dutifully created a Element Host that can show the following WPF object:

<UserControl x:Class="LightBoxTest.LightBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300" Background="Transparent">
    <Grid Name="dialogHolder" Background="Transparent" Opacity="1">
        <Rectangle Name="rectangle1" Stroke="White" Fill="Black" RadiusX="10" RadiusY="10" Opacity="0.5" />
        <StackPanel Name="stackPanel1" Background="Transparent" Height="300" VerticalAlignment="Top">
            <Rectangle Name="spacer" Opacity="0" Stroke="Gray" Fill="White" RadiusX="10" RadiusY="10" Height="100" Width="300" />
            <Grid Height="100" Name="contentHolder" Width="250">
                <Rectangle Name="dialog" Stroke="Gray" Fill="White" RadiusX="10" RadiusY="10" Height="100" Width="250" />
            </Grid>
        </StackPanel>
    </Grid>
</UserControl>

The trouble is that the Controls on the WinForm Form do not render and the WPF just obliterates them on the screen.

The element host is created like:

dialogHost = new ElementHost(); 
dialogHost.Child = dialog;
dialogHost.BackColorTransparent = true;
dialogHost.BringToFront();  
dialogHost.Show();

Is there something I should be doing and Im not?

Are there known issues about showing transparent WPF controls over Winforms?

Any articals that may help?

Note: This question is related to this question

回答1:

I think you're running into an airspace issue. AFAIK, you can't mix WPF transparency and ElementHost transparency since the ElementHost owns the airspace.

There's a short blurb in the link about creating non-rectangular hwnds to host WPF content, and that may get you farther.

Perhaps you can consider migrating more of the WinForms app to WPF?



回答2:

You should read this :Black background before loading a wpf controll when using ElementHost Just hide & show it (not cool but works)



回答3:

That seems like the interop airspace problem.



回答4:

You probably already tried this, but how about setting the Opacity on the User Control?