如何:在属性值更改时触发动画

更新:2007 年 11 月

本示例演示属性值更改时如何使用 Trigger 来启动 Storyboard。您可以在 StyleControlTemplateDataTemplate 中使用 Trigger

示例

下面的示例在当 ButtonIsMouseOver 属性成为 true 时使用 Trigger 对该按钮的 Opacity 进行动画处理。

<!-- PropertyTriggerExample.xaml
     Shows how to use property triggers to start animations. -->
<Page
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  WindowTitle="Animate Properties with Storyboards">
  <Page.Resources>

    <Style x:Key="PropertyTriggerExampleButtonStyle" TargetType="{x:Type Button}">

      <Setter Property="Opacity" Value="0.25" />

      <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">

          <Trigger.EnterActions>
            <BeginStoryboard>
              <Storyboard>
                <DoubleAnimation Storyboard.TargetProperty="Opacity"
                  To="1" Duration="0:0:1" />
              </Storyboard>
            </BeginStoryboard>
          </Trigger.EnterActions>
          <Trigger.ExitActions>
            <BeginStoryboard>
              <Storyboard>
                <DoubleAnimation Storyboard.TargetProperty="Opacity"
                  To="0.25" Duration="0:0:1" />
              </Storyboard>
            </BeginStoryboard>
          </Trigger.ExitActions>          
        </Trigger>               
      </Style.Triggers>    
    </Style>
  </Page.Resources>

  <StackPanel Margin="20">

    <Button Style="{StaticResource PropertyTriggerExampleButtonStyle}">
      Move the mouse over me.
    </Button>

  </StackPanel>
</Page>

属性 Trigger 对象所应用的动画的行为比 EventTrigger 动画或使用 Storyboard 方法启动的动画的行为更复杂一些。 它们在“提交”时使用的是其他 Trigger 对象定义的动画,但是在编写时使用 EventTrigger 和方法触发的动画。

请参见

概念

属性动画技术概述

演示图板概述

参考

Trigger