Condividi tramite


How to: Trigger an Animation When a Property Value Changes

This example shows how to use a Trigger to start a Storyboard when a property value changes. You can use a Trigger inside a Style, ControlTemplate, or DataTemplate.

Example

The following example uses a Trigger to animate the Opacity of a Button when its IsMouseOver property becomes true.

<!-- 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>

Animations applied by property Trigger objects behave in a more complex fashion than EventTrigger animations or animations started using Storyboard methods. They "handoff" with animations defined by other Trigger objects, but compose with EventTrigger and method-triggered animations.

See Also

Reference

Trigger

Concepts

Property Animation Techniques Overview
Storyboards Overview