次の方法で共有


方法: 要素またはブラシの不透明度をアニメーション化する

フレームワーク要素をフェードインまたはフェードアウトするには、その Opacity プロパティをアニメーション化するか、描画に使用する Brush (またはブラシ) の Opacity プロパティをアニメーション化できます。 要素の不透明度をアニメーション化すると、要素とその子要素が視界にフェードインしたりフェードアウトしたりしますが、要素の描画に用いるブラシをアニメーション化すると、どの部分をフェードさせるかをより選択的に制御できます。 たとえば、ボタンの背景の描画に使用するブラシの不透明度をアニメーション化できます。 ボタンの背景が表示されたり消えたりする一方で、そのテキストは完全に不透明なままになります。

手記

BrushOpacity をアニメーション化すると、要素の Opacity プロパティをアニメーション化するよりもパフォーマンス上の利点があります。

次の例では、2 つのボタンがアニメーション化され、フェード インとフェード アウトが表示されます。 最初の Button の不透明度は、1.0 から 5 秒間の Duration0.0 にアニメーション化されます。 2 番目のボタンもアニメーション化されますが、Background の描画に使用される SolidColorBrush の不透明度は、ボタン全体の不透明度ではなくアニメーション化されます。 この例を実行すると、最初のボタンは完全にフェードインおよびフェードアウトし、2 番目のボタンの背景のみがフェードインおよびフェードアウトします。 テキストと罫線は完全に不透明なままです。

<!-- OpacityAnimationExample.xaml
     This example shows how to animate the opacity of objects, 
     making them fade in and out of view. -->
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  WindowTitle="Opacity Animation Example" Background="White">
  <StackPanel Margin="20">

    <!-- Clicking this button animates its opacity. -->
    <Button Name="opacityAnimatedButton">
      A Button
      <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
          <BeginStoryboard>
            <Storyboard>
              <DoubleAnimation 
                Storyboard.TargetName="opacityAnimatedButton"
                Storyboard.TargetProperty="(Button.Opacity)" 
                From="1" To="0" Duration="0:0:5" AutoReverse="True"  /> 
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Button.Triggers>
    </Button>

    <!-- Clicking this button animates the opacity of the brush
         used to paint its background. -->
    <Button>
      A Button
      <Button.Background>
        <SolidColorBrush x:Name="MyAnimatedBrush" Color="Orange" />
      </Button.Background>
      <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
          <BeginStoryboard>
            <Storyboard>
              <DoubleAnimation 
                Storyboard.TargetName="MyAnimatedBrush"
                Storyboard.TargetProperty="(Brush.Opacity)" 
                From="1" To="0" Duration="0:0:5" AutoReverse="True"  />  
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Button.Triggers>         
    </Button>
  </StackPanel>
</Page>

この例では、コードは省略されています。 完全なサンプルでは、LinearGradientBrush内の Color の不透明度をアニメーション化する方法も示しています。 完全なサンプルについては、「要素サンプルの不透明度をアニメーション化する を参照してください。