How to: Make a UIElement Transparent or Semi-Transparent
This example shows how to make a UIElement transparent or semi-transparent. To make an element transparent or semi-transparent, you set its Opacity property. A value of 0.0 makes the element completely transparent, while a value of 1.0 makes the element completely opaque. A value of 0.5 makes the element 50% opaque, and so on. An element's Opacity is set to 1.0 by default.
The following example sets the Opacity of a button to 0.25, making it and its contents (in this case, the button's text) 25% opaque.
<!-- The image contained within this button has an effective opacity of 0.125 (0.25 * 0.5 = 0.125). --> <Button Opacity="0.25"> <StackPanel Orientation="Horizontal"> <TextBlock VerticalAlignment="Center" Margin="10">A Button</TextBlock> <Image Source="sampleImages\berries.jpg" Width="50" Height="50" Opacity="0.5"/> </StackPanel> </Button>
' ' The image contained within this button has an ' effective opacity of 0.125 (0.25*0.5 = 0.125) ' Dim myImageButton As New Button() myImageButton.Opacity = New Double() myImageButton.Opacity = 0.25 Dim myImageStackPanel As New StackPanel() myImageStackPanel.Orientation = Orientation.Horizontal Dim myTextBlock As New TextBlock() myTextBlock.VerticalAlignment = VerticalAlignment.Center myTextBlock.Margin = New Thickness(10) myTextBlock.Text = "A Button" myImageStackPanel.Children.Add(myTextBlock) Dim myImage As New Image() Dim myBitmapImage As New BitmapImage() myBitmapImage.BeginInit() myBitmapImage.UriSource = New Uri("sampleImages/berries.jpg",UriKind.Relative) myBitmapImage.EndInit() myImage.Source = myBitmapImage Dim myImageBrush As New ImageBrush(myBitmapImage) myImage.Width = 50 myImage.Height = 50 myImage.Opacity = 0.5 myImageStackPanel.Children.Add(myImage) myImageButton.Content = myImageStackPanel
Another way to control the opacity of an element is to set the opacity of the Brush that paints the element. This approach enables you to selectively alter the opacity of portions of an element, and provides performance benefits over using the element's Opacity property. The following example sets the Opacity of a SolidColorBrush used to paint the button's Background is set to 0.25. As a result, the brush's background is 25% opaque, but its contents (the button's text) remain 100% opaque.
' ' This button's background is made 25% opaque, ' but its text remains 100% opaque. ' Dim myOpaqueTextButton As New Button() Dim mySolidColorBrush As New SolidColorBrush(Colors.Gray) mySolidColorBrush.Opacity = 0.25 myOpaqueTextButton.Background = mySolidColorBrush myOpaqueTextButton.Content = "A Button"
You may also control the opacity of individual colors within a brush. For more information about colors and brushes, see Painting with Solid Colors and Gradients Overview. For an example showing how to animate an element's opacity, see How to: Animate the Opacity of an Element or Brush.