如何:使 UIElement 呈现为透明或半透明

此示例演示如何使 UIElement 透明或半透明。 若要使元素透明或半透明,请设置其 Opacity 属性。 0.0 的值使元素完全透明,而 1.0 的值使元素完全不透明。 值为 0.5,元素 50% 不透明,依此类推。 默认情况下,元素的 Opacity 设置为 1.0

以下示例将按钮 Opacity 设置为 0.25,使其及其内容(在本例中为按钮的文本)25% 不透明。

<!-- Both the button and its text are made 25% opaque. -->
<Button Opacity="0.25">A Button</Button>
//
// Both the button and its text are made 25% opaque.
//
Button myTwentyFivePercentOpaqueButton = new Button();
myTwentyFivePercentOpaqueButton.Opacity = new Double();
myTwentyFivePercentOpaqueButton.Opacity = 0.25;
myTwentyFivePercentOpaqueButton.Content = "A Button";

如果元素的内容有自己的 Opacity 设置,则这些值将与包含的元素 Opacity 相乘。

以下示例将按钮的 Opacity 设置为 0.25,并将按钮中包含的 Image 控件的 Opacity 设置为 0.5。 因此,图像显示为 12.5% 不透明:0.25 * 0.5 = 0.125。

<!-- 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);
//
Button myImageButton = new Button();
myImageButton.Opacity = new Double();
myImageButton.Opacity = 0.25;

StackPanel myImageStackPanel = new StackPanel();
myImageStackPanel.Orientation = Orientation.Horizontal;

TextBlock myTextBlock = new TextBlock();
myTextBlock.VerticalAlignment = VerticalAlignment.Center;
myTextBlock.Margin = new Thickness(10);
myTextBlock.Text = "A Button";
myImageStackPanel.Children.Add(myTextBlock);

Image myImage = new Image();
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri("sampleImages/berries.jpg",UriKind.Relative);
myBitmapImage.EndInit();
myImage.Source = myBitmapImage;
ImageBrush myImageBrush = new ImageBrush(myBitmapImage);
myImage.Width = 50;
myImage.Height = 50;
myImage.Opacity = 0.5;
myImageStackPanel.Children.Add(myImage);
myImageButton.Content = myImageStackPanel;

控制元素不透明度的另一种方法是设置绘制元素的 Brush 的不透明度。 此方法使你能够选择性地改变元素部分的不透明度,相较于使用元素的Opacity 属性,此方法在性能上有优势。 以下示例将用于绘制按钮的 BackgroundSolidColorBrushOpacity 设置为 0.25。 因此,画笔的背景为 25% 不透明,但其内容(按钮的文本)仍为 100% 不透明。

<!-- This button's background is made 25% opaque, but its
     text remains 100% opaque. -->
<Button>
  <Button.Background>
    <SolidColorBrush Color="Gray" Opacity="0.25" />
  </Button.Background>
  A Button
</Button>
//
//  This button's background is made 25% opaque,
// but its text remains 100% opaque.
//
Button myOpaqueTextButton = new Button();
SolidColorBrush mySolidColorBrush = new SolidColorBrush(Colors.Gray);
mySolidColorBrush.Opacity = 0.25;
myOpaqueTextButton.Background = mySolidColorBrush;
myOpaqueTextButton.Content = "A Button";

还可以控制画笔中各个颜色的不透明度。 有关颜色和画笔的详细信息,请参阅 使用纯色和渐变绘制概述。 有关如何对元素的不透明度进行动画处理的示例,请参阅 对元素或 Brush的不透明度进行动画处理。