Building Transparent Controls in WPF


All WPF controls are inherited from UIElement. The Opacity property of UIElement is used to set transparency of a control. The value of Opacity falls between 0.0 and 1.0 where 0.0 is fully transparent and 1.0 is fully opaque.

The following code snippet creates a button control.

<Button Width="200" Height="30" >

    Click Me!

</Button>

The output looks like Figure 1.

tpImg1.gif

Figure 1

The following code sets Opacity value of the Button control to 50%.

 

<Button Width="200" Height="30" Opacity="0.5">

    Click Me!

</Button>


The new output looks like Figure 2

 


tpImg2.gif

Figure 2

 

 

Now let's say you want to create a Button where only background of the Button will be transparent but text will not. We can use Background property of Button.

<Button Width="200" Height="30" >

    <Button.Background>

        <SolidColorBrush Color="Gray" Opacity="0.50" />

    </Button.Background>

    Click Me!

</Button>

The new output looks like Figure 3.

 

tpIm3.gif

Figure 3

Now let's say you want to create a Button where only background of the Button will be transparent but you want no transparency on the content of the Button, you can simply use Button Background property to set Opacity.  

<Button Width="200" Height="30" >

    <Button.Background>

        <SolidColorBrush Color="Gray" Opacity="0.50" />

    </Button.Background>

    Click Me!

</Button>

The new output looks like Figure 4.

 

tpImg4.gif

Figure 4

If you set Opacity on both Button and its contents, the opacity will be multiplied. For example, the following code sets Opacity of Button and as well as the background.

<Button Width="200" Height="30" Opacity="0.50" >

    <Button.Background>

        <SolidColorBrush Color="Gray" Opacity="0.50" />

    </Button.Background>

    Click Me!

</Button>

The new output looks like Figure 5, where Opacity of background is 0.50 x 0.50 = 0.25.

tpImg5.gif

Figure 5

The following code snippet creates a Button control and sets its Opacity value dynamically.

private void CreateTransparentControls()

{

    Button tpButton = new Button();

    tpButton.Width = 200;

    tpButton.Height = 30;

    SolidColorBrush grayBrush = new SolidColorBrush(Colors.Gray);

    grayBrush.Opacity = 0.25;

    tpButton.Background = grayBrush;

    tpButton.Content = "Click Me!";

 

    // RootLayout is root Grid container on the Window

    RootLayout.Children.Add(tpButton);

}