Change Background opacity without changing content opacity

Idan Shechter picture Idan Shechter · Sep 28, 2012 · Viewed 15.6k times · Source

I wanted to know how can I change the opacity of the background of the WPF Window without effecting the inner child controls. When I change the Window property 'Opacity' to 0.5 I do get a semi-transparent window, but the image inside the window also inherited the 0.5 opacity value, so how can I just make the opacity for the window only?

Answer

evanb picture evanb · Sep 28, 2012

The window is the parent container of everything so setting the opacity on the window will effect everything that it contains. I think what you want to do is change the Opacity of the Window.Background.

Enabling a window to do transparency involves a couple things to be added. First, you will need to set Window.AllowsTransparency = True and also set the Window.WindowStyle = None. WindowStyle.None creates a window without the minimize, maximize, and close buttons in the window chrome so you'll have to handle that in the application yourself along with resizing and moving the window. After that's all done, then you can set the Window.Background to have a brush with an Opacity set on it.

The following code sample will show you how to have the window always transparent and set the opacity of the window background to have a different opacity.

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="WpfApplication1.MainWindow"
        x:Name="Window"
        WindowStyle="None"
        AllowsTransparency="True">
    <Window.Background>
        <SolidColorBrush Color="White" Opacity="0.5"/>
    </Window.Background>
    <Grid>
        <!--Window Content-->
    </Grid>
</Window>

You can always set the window background to transparent if you only want the elements in the window to be visible.