Share via


HOW TO:當屬性值變更時觸發動畫

更新:2007 年 11 月

本範例顯示如何使用 Trigger,在屬性值變更時啟動 Storyboard。您可以在 StyleControlTemplateDataTemplate 內使用 Trigger

範例

下列範例會使用 Trigger,在 ButtonIsMouseOver 屬性變成 true 時將它的 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