動畫概觀Animation Overview

Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 提供一組強大的圖形和版面配置功能,可讓您建立吸引人的使用者介面和吸引人的檔。Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) provides a powerful set of graphics and layout features that enable you to create attractive user interfaces and appealing documents. 動畫可以讓漂亮的使用者介面更美觀而實用。Animation can make an attractive user interface even more spectacular and usable. 只要以動畫顯示背景色彩或套用動畫 Transform,您就可以建立生動的螢幕轉換,或提供有用的視覺提示。By just animating a background color or applying an animated Transform, you can create dramatic screen transitions or provide helpful visual cues.

本總覽提供 WPFWPF 動畫和計時系統的簡介。This overview provides an introduction to the WPFWPF animation and timing system. 它著重在使用分鏡腳本 WPFWPF 物件的動畫。It focuses on the animation of WPFWPF objects by using storyboards.

動畫簡介Introducing Animations

動畫是快速循環一系列影像,而每個影像與上一個影像稍有不同所產生的一種錯覺。Animation is an illusion that is created by quickly cycling through a series of images, each slightly different from the last. 大腦將一組影像認知為一個在變化的場景。The brain perceives the group of images as a single changing scene. 在影片中,此種錯覺是利用每秒拍攝許多照片或畫面的數位相機所產生。In film, this illusion is created by using cameras that record many photographs, or frames, each second. 當投影機播放畫面時,觀眾就會看到移動的圖片。When the frames are played back by a projector, the audience sees a moving picture.

電腦上的動畫很類似如此。Animation on a computer is similar. 例如,讓矩形繪圖淡出畫面的程式可能如下運作。For example, a program that makes a drawing of a rectangle fade out of view might work as follows.

  • 程式建立計時器。The program creates a timer.

  • 程式檢查設定間隔處的計時器,以查看經過多少時間。The program checks the timer at set intervals to see how much time has elapsed.

  • 每當程式檢查計時器時,會根據經過多少時間來計算矩形目前的不透明度值。Each time the program checks the timer, it computes the current opacity value for the rectangle based on how much time has elapsed.

  • 然後程式使用新值更新矩形,並重新繪製矩形。The program then updates the rectangle with the new value and redraws it.

WPFWPF之前,Microsoft Windows 開發人員必須建立和管理自己的計時系統,或使用特殊的自訂程式庫。Prior to WPFWPF, Microsoft Windows developers had to create and manage their own timing systems or use special custom libraries. WPFWPF 包含有效率的計時系統,透過 managed 程式碼和 Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) 公開,而且已緊密整合到 WPFWPF 架構中。includes an efficient timing system that is exposed through managed code and Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) and that is deeply integrated into the WPFWPF framework. WPFWPF 動畫可讓您輕鬆以動畫顯示控制項和其他圖形物件。animation makes it easy to animate controls and other graphical objects.

WPFWPF 會有效率地處理管理計時系統以及重新繪製畫面的所有幕後工作。handles all the behind-the-scenes work of managing a timing system and redrawing the screen efficiently. 它提供的計時類別,可讓您專注在您想要建立的效果,而不是達成這些效果的技術。It provides timing classes that enable you to focus on the effects you want to create, instead of the mechanics of achieving those effects. WPFWPF 也公開您的類別可以繼承的動畫基底類別,方便您建立您自己的動畫,以產生自訂的動畫。also makes it easy to create your own animations by exposing animation base classes from which your classes can inherit, to produce customized animations. 這些自訂動畫可以獲得標準動畫類別的許多效能優勢。These custom animations gain many of the performance benefits of the standard animation classes.

WPF 屬性動畫系統WPF Property Animation System

如果您瞭解有關計時系統的一些重要概念,WPFWPF 動畫可能比較容易使用。If you understand a few important concepts about the timing system, WPFWPF animations can be easier to use. 最重要的是,在 WPFWPF中,您可以藉由將動畫套用至其個別屬性來建立物件動畫。Most important is that, in WPFWPF, you animate objects by applying animation to their individual properties. 例如,若要讓 framework 元素成長,您可以建立其 WidthHeight 屬性的動畫。For example, to make a framework element grow, you animate its Width and Height properties. 若要讓物件淡出視野,您可以建立其 Opacity 屬性的動畫。To make an object fade from view, you animate its Opacity property.

如果要讓屬性具備動畫功能,必須符合下列三個需求︰For a property to have animation capabilities, it must meet the following three requirements:

  • 必須是相依性屬性。It must be a dependency property.

  • 它必須屬於繼承自 DependencyObject 並實 IAnimatable 介面的類別。It must belong to a class that inherits from DependencyObject and implements the IAnimatable interface.

  • 必須有相容的動畫類型。There must be a compatible animation type available. (如果 WPFWPF 沒有提供,您可以自行建立。(If WPFWPF does not provide one, you can create your own. 請參閱自訂動畫總覽)。See the Custom Animations Overview.)

WPFWPF 包含許多具有 IAnimatable 屬性的物件。contains many objects that have IAnimatable properties. ButtonTabControl等控制項,以及 PanelShape 物件繼承自 DependencyObjectControls such as Button and TabControl, and also Panel and Shape objects inherit from DependencyObject. 這些項目的大部分屬性是相依性屬性。Most of their properties are dependency properties.

您幾乎可以在任何地方 (包括在樣式和控制項範本中) 使用動畫。You can use animations almost anywhere, which includes in styles and control templates. 動畫不必是視覺物件。如果不屬於使用者介面部分的物件符合本節所描述的準則,也可以以動畫顯示這些物件。Animations do not have to be visual; you can animate objects that are not part of the user interface if they meet the criteria that are described in this section.

範例︰讓元素淡入又淡出畫面Example: Make an Element Fade In and Out of View

這個範例示範如何使用 WPFWPF 動畫,以動畫顯示相依性屬性的值。This example shows how to use a WPFWPF animation to animate the value of a dependency property. 它會使用 DoubleAnimation,這是產生 Double 值的動畫類型,用來建立 RectangleOpacity 屬性的動畫。It uses a DoubleAnimation, which is a type of animation that generates Double values, to animate the Opacity property of a Rectangle. 因此,Rectangle 淡入和移出畫面。As a result, the Rectangle fades in and out of view.

範例的第一個部分會建立 Rectangle 元素。The first part of the example creates a Rectangle element. 接下來的步驟示範如何建立動畫,並將其套用至矩形的 Opacity 屬性。The steps that follow show how to create an animation and apply it to the rectangle's Opacity property.

以下顯示如何在 XAML 的 StackPanel 中建立 Rectangle 元素。The following shows how to create a Rectangle element in a StackPanel in XAML.

<StackPanel Margin="10">
    <Rectangle
        Name="MyRectangle"
        Width="100" 
        Height="100"
        Fill="Blue">
    </Rectangle>
</StackPanel>

以下顯示如何在程式碼的 StackPanel 中建立 Rectangle 元素。The following shows how to create a Rectangle element in a StackPanel in code.

var myPanel = new StackPanel();
myPanel.Margin = new Thickness(10);

var myRectangle = new Rectangle();
myRectangle.Name = "myRectangle";
this.RegisterName(myRectangle.Name, myRectangle);
myRectangle.Width = 100;
myRectangle.Height = 100;
myRectangle.Fill = Brushes.Blue;
myPanel.Children.Add(myRectangle);
this.Content = myPanel;
Dim myPanel As New StackPanel()
myPanel.Margin = New Thickness(10)

Dim myRectangle As New Rectangle()
myRectangle.Name = "myRectangle"
Me.RegisterName(myRectangle.Name, myRectangle)
myRectangle.Width = 100
myRectangle.Height = 100
myRectangle.Fill = Brushes.Blue

myPanel.Children.Add(myRectangle)
Me.Content = myPanel

第 1 部分︰建立 DoubleAnimationPart 1: Create a DoubleAnimation

讓元素淡入和移出視圖的其中一種方式,就是以動畫顯示其 Opacity 屬性。One way to make an element fade in and out of view is to animate its Opacity property. 因為 Opacity 屬性的類型為 Double,所以您需要會產生雙精度浮點數的動畫。Because the Opacity property is of type Double, you need an animation that produces double values. DoubleAnimation 就是其中一個動畫。A DoubleAnimation is one such animation. DoubleAnimation 會建立兩個雙精度浮點數之間的轉換。A DoubleAnimation creates a transition between two double values. 若要指定其起始值,請設定其 From 屬性。To specify its starting value, you set its From property. 若要指定其結束值,請設定其 To 屬性。To specify its ending value, you set its To property.

  1. 1.0 的不透明度值會使物件完全不透明,而不透明度值 0.0 會使其完全不可見。An opacity value of 1.0 makes the object completely opaque, and an opacity value of 0.0 makes it completely invisible. 若要讓動畫從 1.0 轉換成 0.0 您將其 From 屬性設為 1.0,並將其 To 屬性設定為 [0.0]。To make the animation transition from 1.0 to 0.0 you set its From property to 1.0 and its To property to 0.0. 以下顯示如何在 XAML 中建立 DoubleAnimationThe following shows how to create a DoubleAnimation in XAML.

    <DoubleAnimation From="1.0" To="0.0" />
    

    以下顯示如何在程式碼中建立 DoubleAnimationThe following shows how to create a DoubleAnimation in code.

    var myDoubleAnimation = new DoubleAnimation();
    myDoubleAnimation.From = 1.0;
    myDoubleAnimation.To = 0.0;
    
    Dim myDoubleAnimation As New DoubleAnimation()
    myDoubleAnimation.From = 1.0
    myDoubleAnimation.To = 0.0
    
  2. 接下來,您必須指定 DurationNext, you must specify a Duration. 動畫的 Duration 會指定從起始值到其目的地值所需的時間。The Duration of an animation specifies how long it takes to go from its starting value to its destination value. 以下顯示如何在 XAML 中將 Duration 設定為五秒。The following shows how to set the Duration to five seconds in XAML.

    <DoubleAnimation From="1.0" To="0.0" Duration="0:0:5" />
    

    以下顯示如何在程式碼中將 Duration 設為5秒。The following shows how to set the Duration to five seconds in code.

    myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));
    
    myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(5))
    
  3. 先前的程式碼示範了從 1.0 轉換為 0.0的動畫,這會導致目標元素從完全不透明淡出到完全不可見。The previous code showed an animation that transitions from 1.0 to 0.0, which causes the target element to fade from completely opaque to completely invisible. 若要讓元素在會消失之後淡回視野,請將動畫的 [AutoReverse] 屬性設定為 [true]。To make the element fade back into view after it vanishes, set the AutoReverse property of the animation to true. 若要無限期地重複動畫,請將其 [RepeatBehavior] 屬性設定為 [Forever]。To make the animation repeat indefinitely, set its RepeatBehavior property to Forever. 以下顯示如何在 XAML 中設定 AutoReverseRepeatBehavior 屬性。The following shows how to set the AutoReverse and RepeatBehavior properties in XAML.

    <DoubleAnimation From="1.0" To="0.0" Duration="0:0:5" AutoReverse="True" RepeatBehavior="Forever"/>
    

    以下顯示如何在程式碼中設定 AutoReverseRepeatBehavior 屬性。The following shows how to set the AutoReverse and RepeatBehavior properties in code.

    myDoubleAnimation.AutoReverse = true;
    myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
    
    myDoubleAnimation.AutoReverse = True
    myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever
    

第 2 部分︰建立分鏡腳本Part 2: Create a Storyboard

若要將動畫套用至物件,您可以建立 Storyboard 並使用 TargetNameTargetProperty 附加屬性來指定要建立動畫的物件和屬性。To apply an animation to an object, you create a Storyboard and use the TargetName and TargetProperty attached properties to specify the object and property to animate.

  1. 建立 Storyboard 並將動畫新增為其子系。Create the Storyboard and add the animation as its child. 以下顯示如何在 XAML 中建立 StoryboardThe following shows how to create the Storyboard in XAML.

    <Storyboard>
        <DoubleAnimation
            From="1.0" To="0.0" Duration="0:0:1" 
            AutoReverse="True" RepeatBehavior="Forever" />
    </Storyboard>
    

    若要在程式碼中建立 Storyboard,請在類別層級宣告 Storyboard 變數。To create the Storyboard in code, declare a Storyboard variable at the class level.

    public partial class MainWindow : Window
    {
        private Storyboard myStoryboard;
    
    Class MainWindow
    
        Private myStoryboard As Storyboard
    

    然後初始化 Storyboard,並將動畫新增為其子系。Then initialize the Storyboard and add the animation as its child.

    myStoryboard = new Storyboard();
    myStoryboard.Children.Add(myDoubleAnimation);
    
    myStoryboard = New Storyboard()
    myStoryboard.Children.Add(myDoubleAnimation)
    
  2. Storyboard 必須知道要將動畫套用至何處。The Storyboard has to know where to apply the animation. 使用 Storyboard.TargetName 附加屬性來指定要建立動畫的物件。Use the Storyboard.TargetName attached property to specify the object to animate. 以下顯示如何將 DoubleAnimation 的目標名稱設定為 XAML 中 MyRectangleThe following shows how to set the target name of the DoubleAnimation to MyRectangle in XAML.

    <Storyboard>
        <DoubleAnimation
            Storyboard.TargetName="MyRectangle" 
            From="1.0" To="0.0" Duration="0:0:1" 
            AutoReverse="True" RepeatBehavior="Forever" />
    </Storyboard>
    

    以下顯示如何在程式碼中將 DoubleAnimation 的目標名稱設定為 MyRectangleThe following shows how to set the target name of the DoubleAnimation to MyRectangle in code.

    Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name);
    
    Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name)
    
  3. 使用 TargetProperty 附加屬性來指定要建立動畫的屬性。Use the TargetProperty attached property to specify the property to animate. 以下顯示動畫如何設定為以 XAML 中 RectangleOpacity 屬性為目標。The following shows how the animation is configured to target the Opacity property of the Rectangle in XAML.

    <Storyboard>
        <DoubleAnimation
            Storyboard.TargetName="MyRectangle" 
            Storyboard.TargetProperty="Opacity"
            From="1.0" To="0.0" Duration="0:0:5" 
            AutoReverse="True" RepeatBehavior="Forever" />
    </Storyboard>
    

    以下顯示如何設定動畫以程式碼中 RectangleOpacity 屬性為目標。The following shows how the animation is configured to target the Opacity property of the Rectangle in code.

    Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Rectangle.OpacityProperty));
    
    Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.OpacityProperty))
    

如需 TargetProperty 語法和其他範例的詳細資訊,請參閱分鏡腳本總覽For more information about TargetProperty syntax and for additional examples, see the Storyboards Overview.

第 3 部分 (XAML)︰將分鏡腳本與觸發程序建立關聯Part 3 (XAML): Associate the Storyboard with a Trigger

XAMLXAML 中套用和啟動 Storyboard 最簡單的方式,就是使用事件觸發程式。The easiest way to apply and start a Storyboard in XAMLXAML is to use an event trigger. 本節說明如何在 XAML 中將 Storyboard 與觸發程式產生關聯。This section shows how to associate the Storyboard with a trigger in XAML.

  1. 建立 BeginStoryboard 物件,並將您的分鏡腳本與它建立關聯。Create a BeginStoryboard object and associate your storyboard with it. BeginStoryboard 是一種套用和啟動 StoryboardTriggerAction 類型。A BeginStoryboard is a type of TriggerAction that applies and starts a Storyboard.

    <BeginStoryboard>
      <Storyboard>
        <DoubleAnimation
          Storyboard.TargetName="MyRectangle" 
          Storyboard.TargetProperty="Opacity"
          From="1.0" To="0.0" Duration="0:0:5" 
          AutoReverse="True" RepeatBehavior="Forever" />
      </Storyboard>
    </BeginStoryboard>
    
  2. 建立 EventTrigger,並將 BeginStoryboard 新增至其 Actions 集合。Create an EventTrigger and add the BeginStoryboard to its Actions collection. EventTriggerRoutedEvent 屬性設定為您要啟動 Storyboard的路由事件。Set the RoutedEvent property of the EventTrigger to the routed event that you want to start the Storyboard. (如需路由事件的詳細資訊,請參閱路由事件總覽)。(For more information about routed events, see the Routed Events Overview.)

    <!-- Animates the rectangle's opacity. -->
    <EventTrigger RoutedEvent="Rectangle.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimation
            Storyboard.TargetName="MyRectangle" 
            Storyboard.TargetProperty="Opacity"
            From="1.0" To="0.0" Duration="0:0:5" 
            AutoReverse="True" RepeatBehavior="Forever" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
    
  3. EventTrigger 加入至矩形的 Triggers 集合。Add the EventTrigger to the Triggers collection of the Rectangle.

    <Rectangle
      Name="MyRectangle"
      Width="100" 
      Height="100"
      Fill="Blue">
      <Rectangle.Triggers>
        <!-- Animates the rectangle's opacity. -->
        <EventTrigger RoutedEvent="Rectangle.Loaded">
          <BeginStoryboard>
            <Storyboard>
              <DoubleAnimation
                Storyboard.TargetName="MyRectangle" 
                Storyboard.TargetProperty="Opacity"
                From="1.0" To="0.0" Duration="0:0:5" 
                AutoReverse="True" RepeatBehavior="Forever" />
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
      </Rectangle.Triggers>
    </Rectangle>
    

第 3 部分 (程式碼)︰將分鏡腳本與事件處理常式建立關聯Part 3 (Code): Associate the Storyboard with an Event Handler

在程式碼中套用和啟動 Storyboard 最簡單的方式,就是使用事件處理常式。The easiest way to apply and start a Storyboard in code is to use an event handler. 本節說明如何在程式碼中將 Storyboard 與事件處理常式產生關聯。This section shows how to associate the Storyboard with an event handler in code.

  1. 註冊矩形的 Loaded 事件。Register for the Loaded event of the rectangle.

    myRectangle.Loaded += new RoutedEventHandler(myRectangleLoaded);
    
    AddHandler myRectangle.Loaded, AddressOf myRectangleLoaded
    
  2. 宣告事件處理常式。Declare the event handler. 在事件處理常式中,使用 Begin 方法來套用分鏡腳本。In the event handler, use the Begin method to apply the storyboard.

    private void myRectangleLoaded(object sender, RoutedEventArgs e)
    {
        myStoryboard.Begin(this);
    }
    
    Private Sub myRectangleLoaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        myStoryboard.Begin(Me)
    End Sub
    

完整範例Complete Example

下圖顯示如何建立在 XAML 中淡入和移出視圖的矩形。The following shows how to create a rectangle that fades in and out of view in XAML.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel Margin="10">
            <Rectangle
                Name="MyRectangle"
                Width="100" 
                Height="100"
                Fill="Blue">
                <Rectangle.Triggers>
                    <!-- Animates the rectangle's opacity. -->
                    <EventTrigger RoutedEvent="Rectangle.Loaded">
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation
                                    Storyboard.TargetName="MyRectangle" 
                                    Storyboard.TargetProperty="Opacity"
                                    From="1.0" To="0.0" Duration="0:0:5" 
                                    AutoReverse="True" RepeatBehavior="Forever" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Rectangle.Triggers>
            </Rectangle>
        </StackPanel>
    </Grid>
</Window>

下面顯示如何在程式碼中建立淡入又淡出畫面的矩形。The following shows how to create a rectangle that fades in and out of view in code.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        private Storyboard myStoryboard;

        public MainWindow()
        {
            InitializeComponent();

            StackPanel myPanel = new StackPanel();
            myPanel.Margin = new Thickness(10);

            Rectangle myRectangle = new Rectangle();
            myRectangle.Name = "myRectangle";
            this.RegisterName(myRectangle.Name, myRectangle);
            myRectangle.Width = 100;
            myRectangle.Height = 100;
            myRectangle.Fill = Brushes.Blue;

            DoubleAnimation myDoubleAnimation = new DoubleAnimation();
            myDoubleAnimation.From = 1.0;
            myDoubleAnimation.To = 0.0;
            myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));
            myDoubleAnimation.AutoReverse = true;
            myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever;

            myStoryboard = new Storyboard();
            myStoryboard.Children.Add(myDoubleAnimation);
            Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name);
            Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Rectangle.OpacityProperty));

            // Use the Loaded event to start the Storyboard.
            myRectangle.Loaded += new RoutedEventHandler(myRectangleLoaded);
            myPanel.Children.Add(myRectangle);
            this.Content = myPanel;
        }

        private void myRectangleLoaded(object sender, RoutedEventArgs e)
        {
            myStoryboard.Begin(this);
        }
    }
}
Imports System.Windows.Media.Animation

Class MainWindow

    Private myStoryboard As Storyboard

    Public Sub New()
        InitializeComponent()

        Dim myPanel As New StackPanel()
        myPanel.Margin = New Thickness(10)

        Dim myRectangle As New Rectangle()
        myRectangle.Name = "myRectangle"
        Me.RegisterName(myRectangle.Name, myRectangle)
        myRectangle.Width = 100
        myRectangle.Height = 100
        myRectangle.Fill = Brushes.Blue

        Dim myDoubleAnimation As New DoubleAnimation()
        myDoubleAnimation.From = 1.0
        myDoubleAnimation.To = 0.0
        myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(5))
        myDoubleAnimation.AutoReverse = True
        myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever

        myStoryboard = New Storyboard()
        myStoryboard.Children.Add(myDoubleAnimation)
        Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name)
        Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.OpacityProperty))

        ' Use the Loaded event to start the Storyboard.
        AddHandler myRectangle.Loaded, AddressOf myRectangleLoaded

        myPanel.Children.Add(myRectangle)
        Me.Content = myPanel
    End Sub

    Private Sub myRectangleLoaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        myStoryboard.Begin(Me)
    End Sub

End Class

動畫類型Animation Types

由於動畫會產生屬性值,因此不同的屬性類型有不同的動畫類型。Because animations generate property values, different animation types exist for different property types. 若要以動畫顯示採用 Double的屬性(例如元素的 Width 屬性),請使用會產生 Double 值的動畫。To animate a property that takes a Double, such as the Width property of an element, use an animation that produces Double values. 若要以動畫顯示接受 Point的屬性,請使用會產生 Point 值的動畫等等。To animate a property that takes a Point, use an animation that produces Point values, and so on. 由於不同的屬性類型數目,System.Windows.Media.Animation 命名空間中有數個動畫類別。Because of the number of different property types, there are several animation classes in the System.Windows.Media.Animation namespace. 幸運的是,它們會遵循嚴格的命名慣例方便您區分︰Fortunately, they follow a strict naming convention that makes it easy to differentiate between them:

  • <Type>Animation<Type>Animation

    稱為 "From/To/By" 或「基本」動畫,這些會以動畫顯示開始值到目的地值,或將位移值新增至其開始值。Known as a "From/To/By" or "basic" animation, these animate between a starting and destination value, or by adding an offset value to its starting value.

    • 若要指定開始值,請設定動畫的 From 屬性。To specify a starting value, set the From property of the animation.

    • 若要指定結束值,請設定動畫的 To 屬性。To specify an ending value, set the To property of the animation.

    • 若要指定位移值,請設定動畫的 By 屬性。To specify an offset value, set the By property of the animation.

    本概觀中的範例會使用這些動畫,因為最容易使用。The examples in this overview use these animations, because they are the simplest to use. From/to/By 動畫會在 [從]/[至]/[按動畫] 總覽中詳細說明。From/To/By animations are described in detail in the From/To/By Animations Overview.

  • <Type>AnimationUsingKeyFrames<Type>AnimationUsingKeyFrames

    主要畫面格動畫比 From/To/By 動畫更強大,因為您可以指定任意數目的目標值,甚至可以控制其插補方法。Key frame animations are more powerful than From/To/By animations because you can specify any number of target values and even control their interpolation method. 某些類型只能使用主要畫面格動畫顯示動畫。Some types can only be animated with key frame animations. 主要畫面格動畫會在主要畫面格動畫總覽中詳細說明。Key frame animations are described in detail in the Key-Frame Animations Overview.

  • <Type>AnimationUsingPath<Type>AnimationUsingPath

    路徑動畫可讓您使用幾何路徑以產生動畫的值。Path animations enable you to use a geometric path in order to produce animated values.

  • <Type>AnimationBase<Type>AnimationBase

    當您實作時,以動畫顯示<Type> 值的抽象類別。Abstract class that, when you implement it, animates a <Type> value. 此類別可做為 <Type>Animation 和 <Type>AnimationUsingKeyFrames 類別的基底類別。This class serves as the base class for <Type>Animation and <Type>AnimationUsingKeyFrames classes. 只有當您想要建立您自己的自訂動畫時,才需要直接處理這些類別。You have to deal directly with these classes only if you want to create your own custom animations. 否則,請使用 <Type>Animation 或 KeyFrame<Type>Animation。Otherwise, use a <Type>Animation or KeyFrame<Type>Animation.

在大部分情況下,您會想要使用 <類型> 動畫類別,例如 DoubleAnimationColorAnimationIn most cases, you will want to use the <Type>Animation classes, such as DoubleAnimation and ColorAnimation.

下表顯示數個常見的動畫類型和搭配使用的某些屬性。The following table shows several common animation types and some properties with which they are used.

屬性類型Property type 對應的基本 (From/To/By) 動畫Corresponding basic (From/To/By) animation 對應的主要畫面格動畫Corresponding key frame animation 對應的路徑動畫Corresponding Path Animation 使用範例Usage example
Color ColorAnimation ColorAnimationUsingKeyFrames NoneNone 建立 SolidColorBrushGradientStopColor 的動畫。Animate the Color of a SolidColorBrush or a GradientStop.
Double DoubleAnimation DoubleAnimationUsingKeyFrames DoubleAnimationUsingPath 以動畫顯示 DockPanelWidthButtonHeightAnimate the Width of a DockPanel or the Height of a Button.
Point PointAnimation PointAnimationUsingKeyFrames PointAnimationUsingPath 以動畫顯示 EllipseGeometryCenter 位置。Animate the Center position of an EllipseGeometry.
String NoneNone StringAnimationUsingKeyFrames NoneNone 以動畫顯示 TextBlockTextButtonContentAnimate the Text of a TextBlock or the Content of a Button.

動畫是時間軸Animations Are Timelines

所有的動畫類型都會繼承自 Timeline 類別;因此,所有動畫都是特製化的時間軸類型。All the animation types inherit from the Timeline class; therefore, all animations are specialized types of timelines. Timeline 定義一段時間。A Timeline defines a segment of time. 您可以指定時間軸的計時行為:其 Duration、重複的次數,以及更快速地進行的時間。You can specify the timing behaviors of a timeline: its Duration, how many times it is repeated, and even how fast time progresses for it.

因為動畫是 Timeline,所以也代表一段時間。Because an animation is a Timeline, it also represents a segment of time. 動畫也會在其指定的時間區段(或 Duration)時,計算輸出值。An animation also calculates output values as it progresses through its specified segment of time (or Duration). 隨著動畫進行 (或「播放」),動畫會更新相關聯的屬性。As the animation progresses, or "plays," it updates the property that it is associated with.

三個經常使用的計時屬性為 DurationAutoReverseRepeatBehaviorThree frequently used timing properties are Duration, AutoReverse, and RepeatBehavior.

Duration 屬性The Duration Property

如先前所述,時間軸代表一段時間。As previously mentioned, a timeline represents a segment of time. 該區段的長度取決於時間軸的 Duration,通常是使用 TimeSpan 值來指定。The length of that segment is determined by the Duration of the timeline, which is usually specified by using a TimeSpan value. 當時間軸到達其持續時間結尾時,就是已經完成反覆項目。When a timeline reaches the end of its duration, it has completed an iteration.

動畫會使用其 Duration 屬性來判斷其目前的值。An animation uses its Duration property to determine its current value. 如果您未指定動畫的 Duration 值,則會使用1秒(預設值)。If you do not specify a Duration value for an animation, it uses 1 second, which is the default.

下列語法顯示 Duration 屬性的 Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) 屬性語法的簡化版本。The following syntax shows a simplified version of the Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) attribute syntax for the Duration property.

小時:分鐘:hours : minutes : seconds

下表顯示數個 Duration 設定和其產生的值。The following table shows several Duration settings and their resulting values.

設定Setting 產生的值Resulting value
0:0:5.50:0:5.5 5.5 秒。5.5 seconds.
0:30:5.50:30:5.5 30 分鐘 5.5 秒。30 minutes and 5.5 seconds.
1:30:5.51:30:5.5 1 小時 30 分鐘 5.5 秒。1 hour, 30 minutes, and 5.5 seconds.

在程式碼中指定 Duration 的方法之一,就是使用 FromSeconds 方法來建立 TimeSpan,然後使用該 TimeSpan來宣告新的 Duration 結構。One way to specify a Duration in code is to use the FromSeconds method to create a TimeSpan, then declare a new Duration structure using that TimeSpan.

如需 Duration 值和完整 Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) 語法的詳細資訊,請參閱 Duration 結構。For more information about Duration values and the complete Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) syntax, see the Duration structure.

AutoReverseAutoReverse

AutoReverse 屬性會指定時間軸是否會在到達其 Duration結尾後播放。The AutoReverse property specifies whether a timeline plays backward after it reaches the end of its Duration. 如果您將此動畫屬性設定為 [true],動畫會在到達其 Duration結尾後反轉,並從其結束值播放回其起始值。If you set this animation property to true, an animation reverses after it reaches the end of its Duration, playing from its ending value back to its starting value. 根據預設,此屬性為 falseBy default, this property is false.

RepeatBehaviorRepeatBehavior

RepeatBehavior 屬性會指定時間軸播放的次數。The RepeatBehavior property specifies how many times a timeline plays. 根據預設,時間軸具有 1.0的反復專案計數,這表示它們會播放一次,而且完全不重複。By default, timelines have an iteration count of 1.0, which means they play one time and do not repeat at all.

如需這些屬性和其他屬性的詳細資訊,請參閱計時行為總覽For more information about these properties and others, see the Timing Behaviors Overview.

對屬性套用動畫Applying an Animation to a Property

前幾節說明不同類型的動畫及其計時屬性。The previous sections describe the different types of animations and their timing properties. 本節說明如何對您想要以動畫顯示的屬性套用動畫。This section shows how to apply the animation to the property that you want to animate. Storyboard 物件提供一種將動畫套用至屬性的方式。Storyboard objects provide one way to apply animations to properties. Storyboard 是一種容器時間軸,它會為其所包含的動畫提供目標資訊。A Storyboard is a container timeline that provides targeting information for the animations it contains.

以物件和屬性為目標Targeting Objects and Properties

Storyboard 類別提供 TargetNameTargetProperty 附加的屬性。The Storyboard class provides the TargetName and TargetProperty attached properties. 您對動畫設定這些屬性,就可以告訴動畫要以動畫顯示的內容。By setting these properties on an animation, you tell the animation what to animate. 不過,在以物件為目標顯示動畫之前,物件通常必須要有名稱。However, before an animation can target an object, the object must usually be given a name.

將名稱指派給 FrameworkElement 不同于指派 Freezable 物件的名稱。Assigning a name to a FrameworkElement differs from assigning a name to a Freezable object. 大部分的控制項和面板是架構元素。不過,大部分純圖形物件 (例如筆刷、轉換和幾何) 則是 Freezable 物件。Most controls and panels are framework elements; however, most purely graphical objects, such as brushes, transforms, and geometries, are freezable objects. 如果您不確定類型是 FrameworkElementFreezable,請參閱其參考檔的「繼承階層」一節。If you are not sure whether a type is a FrameworkElement or a Freezable, refer to the Inheritance Hierarchy section of its reference documentation.

  • 若要讓 FrameworkElement 動畫目標,您可以藉由設定其 Name 屬性來指定名稱。To make a FrameworkElement an animation target, you give it a name by setting its Name property. 在程式碼中,您也必須使用 RegisterName 方法,向它所屬的頁面註冊專案名稱。In code, you must also use the RegisterName method to register the element name with the page to which it belongs.

  • 若要在 XAMLXAML中將 Freezable 物件設為動畫目標,您可以使用x:Name指示詞為其指派名稱。To make a Freezable object an animation target in XAMLXAML, you use the x:Name Directive to assign it a name. 在程式碼中,您只需使用 RegisterName 方法,將物件註冊到它所屬的頁面。In code, you just use the RegisterName method to register the object with the page to which it belongs.

下列各節提供在 XAMLXAML 和程式碼中命名元素的範例。The sections that follow provide an example of naming an element in XAMLXAML and code. 如需命名和目標的詳細資訊,請參閱分鏡腳本總覽For more detailed information about naming and targeting, see the Storyboards Overview.

套用和啟動分鏡腳本Applying and Starting Storyboards

若要在 XAMLXAML中啟動分鏡腳本,請將它與 EventTrigger產生關聯。To start a storyboard in XAMLXAML, you associate it with an EventTrigger. EventTrigger 是物件,描述當指定的事件發生時所要採取的動作。An EventTrigger is an object that describes what actions to take when a specified event occurs. 其中一個動作可以是 BeginStoryboard 動作,您可以用來啟動分鏡腳本。One of those actions can be a BeginStoryboard action, which you use to start your storyboard. 事件觸發程序在概念上類似事件處理常式,因為兩者都可讓您指定您的應用程式要如何回應特定事件。Event triggers are similar in concept to event handlers because they enable you to specify how your application responds to a particular event. 與事件處理常式不同的是,事件觸發程式可以在 XAMLXAML中完整描述;不需要其他程式碼。Unlike event handlers, event triggers can be fully described in XAMLXAML; no other code is required.

若要在程式碼中啟動 Storyboard,您可以使用 EventTrigger,或使用 Storyboard 類別的 Begin 方法。To start a Storyboard in code, you can use an EventTrigger or use the Begin method of the Storyboard class.

以互動方式控制分鏡腳本Interactively Control a Storyboard

上一個範例示範了如何在事件發生時啟動 StoryboardThe previous example showed how to start a Storyboard when an event occurs. 您也可以在啟動之後,以互動方式控制 Storyboard:您可以暫停、繼續、停止、將它前進到填滿期間、搜尋和移除 StoryboardYou can also interactively control a Storyboard after it starts: you can pause, resume, stop, advance it to its fill period, seek, and remove the Storyboard. 如需顯示如何以互動方式控制 Storyboard的詳細資訊和範例,請參閱分鏡腳本總覽For more information and an example that shows how to interactively control a Storyboard, see the Storyboards Overview.

動畫結束後,會發生什麼事?What Happens After an Animation Ends?

[FillBehavior] 屬性會指定時間軸結束時的運作方式。The FillBehavior property specifies how a timeline behaves when it ends. 根據預設,時間軸會在結束時開始 FillingBy default, a timeline starts Filling when it ends. Filling 的動畫會保存其最終輸出值。An animation that is Filling holds its final output value.

上一個範例中的 DoubleAnimation 不會結束,因為其 RepeatBehavior 屬性設定為 [Forever]。The DoubleAnimation in the previous example does not end because its RepeatBehavior property is set to Forever. 下列範例使用類似的動畫,以動畫顯示矩形。The following example animates a rectangle by using a similar animation. 與上一個範例不同的是,這個動畫的 RepeatBehaviorAutoReverse 屬性會保留其預設值。Unlike the previous example, the RepeatBehavior and AutoReverse properties of this animation are left at their default values. 因此,動畫在五秒內從 1 開始進行到 0,然後停止。Therefore, the animation progresses from 1 to 0 over five seconds and then stops.

<Rectangle
  Name="MyRectangle"
  Width="100" 
  Height="100"
  Fill="Blue">
  <Rectangle.Triggers>

    <!-- Animates the rectangle's opacity. -->
    <EventTrigger RoutedEvent="Rectangle.Loaded">
      <BeginStoryboard>
        <Storyboard>
          <DoubleAnimation
            Storyboard.TargetName="MyRectangle" 
            Storyboard.TargetProperty="Opacity"
            From="1.0" To="0" Duration="0:0:5" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 1.0;
myDoubleAnimation.To = 0.0;
myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.From = 1.0
myDoubleAnimation.To = 0.0
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(5))

因為其 FillBehavior 不會從 HoldEnd的預設值變更,所以動畫會在結束時保留其最終值0。Because its FillBehavior was not changed from its default value, which is HoldEnd, the animation holds its final value, 0, when it ends. 因此,在動畫結束後,矩形的 Opacity 會維持在0。Therefore, the Opacity of the rectangle remains at 0 after the animation ends. 如果您將矩形的 Opacity 設定為另一個值,則您的程式碼看起來不會有任何作用,因為動畫仍然會影響 Opacity 屬性。If you set the Opacity of the rectangle to another value, your code appears to have no effect, because the animation is still affecting the Opacity property.

若要在程式碼中重新取得動畫屬性的控制權,其中一種方法是使用 BeginAnimation 方法,並為 AnimationTimeline 參數指定 null。One way to regain control of an animated property in code is to use the BeginAnimation method and specify null for the AnimationTimeline parameter. 如需詳細資訊和範例,請參閱使用分鏡腳本建立屬性的動畫後進行設定For more information and an example, see Set a Property After Animating It with a Storyboard.

請注意,雖然設定具有 ActiveFilling 動畫的屬性值不會有任何作用,但屬性值的確會變更。Note that, although setting a property value that has an Active or Filling animation appears to have no effect, the property value does change. 如需詳細資訊,請參閱動畫和計時系統總覽For more information, see the Animation and Timing System Overview.

資料繫結和建立動畫Data Binding and Animating Animations

大部分的動畫屬性可以是資料系結或動畫;例如,您可以建立 DoubleAnimationDuration 屬性的動畫。Most animation properties can be data bound or animated; for example, you can animate the Duration property of a DoubleAnimation. 不過,由於計時系統的運作方式,資料繫結或動畫顯示的動畫不像其他資料繫結或動畫物件。However, because of the way the timing system works, data bound or animated animations do not behave like other data bound or animated objects. 若要了解其行為,了解對屬性套用動畫的意義會很有幫助。To understand their behavior, it helps to understand what it means to apply an animation to a property.

請參閱上一節中的範例,示範如何以動畫顯示矩形的 OpacityRefer to the example in the previous section that showed how to animate the Opacity of a rectangle. 載入上一個範例中的矩形時,其事件觸發程式會套用 StoryboardWhen the rectangle in the previous example is loaded, its event trigger applies the Storyboard. 計時系統會建立 Storyboard 和其動畫的複本。The timing system creates a copy of the Storyboard and its animation. 這些複本會凍結(設為唯讀),並從它們建立 Clock 物件。These copies are frozen (made read-only) and Clock objects are created from them. 這些時鐘會執行以動畫顯示目標屬性的實際工作。These clocks do the actual work of animating the targeted properties.

計時系統會為 DoubleAnimation 建立時鐘,並將其套用至 DoubleAnimationTargetNameTargetProperty 所指定的物件和屬性。The timing system creates a clock for the DoubleAnimation and applies it to the object and property that is specified by the TargetName and TargetProperty of the DoubleAnimation. 在此情況下,計時系統會將時鐘套用至名為 "MyRectangle" 之物件的 Opacity 屬性。In this case, the timing system applies the clock to the Opacity property of the object that is named "MyRectangle."

雖然也會為 Storyboard建立時鐘,但時鐘不會套用至任何屬性。Although a clock is also created for the Storyboard, the clock is not applied to any properties. 其目的是要控制其子時鐘,這是針對 DoubleAnimation所建立的時鐘。Its purpose is to control its child clock, the clock that is created for the DoubleAnimation.

若要讓動畫反映出資料繫結或動畫變更,就必須重新產生動畫的時鐘。For an animation to reflect data binding or animation changes, its clock must be regenerated. 時鐘不會自動產生。Clocks are not regenerated for you automatically. 若要讓動畫反映變更,請使用 BeginStoryboardBegin 方法來重新套用其分鏡腳本。To make an animation reflect changes, reapply its storyboard by using a BeginStoryboard or the Begin method. 當您使用其中一種方法時,動畫會重新啟動。When you use either of these methods, the animation restarts. 在程式碼中,您可以使用 Seek 方法,將分鏡腳本移回先前的位置。In code, you can use the Seek method to shift the storyboard back to its previous position.

如需資料系結動畫的範例,請參閱主要曲線動畫範例For an example of a data bound animation, see Key Spline Animation Sample. 如需動畫和計時系統運作方式的詳細資訊,請參閱動畫和計時系統總覽For more information about how the animation and timing system works, see Animation and Timing System Overview.

顯示動畫的其他方式Other Ways to Animate

本概觀中的範例示範如何使用分鏡腳本顯示動畫。The examples in this overview show how to animate by using storyboards. 當您使用程式碼時,可以使用其他幾種方式顯示動畫。When you use code, you can animate in several other ways. 如需詳細資訊,請參閱屬性動畫技術總覽For more information, see the Property Animation Techniques Overview.

動畫範例Animation Samples

下列範例可以幫助您開始將動畫加入至您的應用程式。The following samples can help you start adding animation to your applications.

標題Title 描述Description
動畫和計時系統概觀Animation and Timing System Overview 描述計時系統如何使用 TimelineClock 類別,這可讓您建立動畫。Describes how the timing system uses the Timeline and Clock classes, which allow you to create animations.
動畫祕訣和訣竅Animation Tips and Tricks 列出解決動畫問題 (例如效能) 的有用祕訣。Lists helpful tips for solving issues with animations, such as performance.
自訂動畫概觀Custom Animations Overview 描述如何使用主要畫面格、動畫類別或每個畫面格回呼來擴充動畫系統。Describes how to extend the animation system with key frames, animation classes, or per-frame callbacks.
From/To/By 動畫概觀From/To/By Animations Overview 描述如何建立在兩個值之間轉換的動畫。Describes how to create an animation that transitions between two values.
主要畫面格動畫概觀Key-Frame Animations Overview 描述如何建立有多個目標值的動畫,包括控制插補方法的能力。Describes how to create an animation with multiple target values, including the ability to control the interpolation method.
Easing 函式Easing Functions 說明如何對動畫套用數學公式以獲得實際的行為,例如彈跳。Explains how to apply mathematical formulas to your animations to get realistic behavior, such as bouncing.
路徑動畫概觀Path Animations Overview 描述如何沿著複雜路徑移動或旋轉物件。Describes how to move or rotate an object along a complex path.
屬性動畫技術概觀Property Animation Techniques Overview 描述使用分鏡腳本的屬性動畫、本機動畫、時鐘和每個畫面格動畫。Describes property animations using storyboards, local animations, clocks, and per-frame animations.
分鏡腳本概觀Storyboards Overview 描述如何使用有多個時間軸的分鏡腳本建立複雜的動畫。Describes how to use storyboards with multiple timelines to create complex animations.
計時行為概觀Timing Behaviors Overview 描述動畫中使用的 Timeline 類型和屬性。Describes the Timeline types and properties used in animations.
計時事件概觀Timing Events Overview 描述 TimelineClock 物件上可用的事件,以在時間軸中的點執行程式碼,例如 [開始]、[暫停]、[繼續]、[略過] 或 [停止]。Describes the events available on the Timeline and Clock objects for executing code at points in the timeline, such as begin, pause, resume, skip, or stop.
「如何」主題How-to Topics 包含在應用程式中使用動畫及時間軸的程式碼範例。Contains code examples for using animations and timelines in your application.
時鐘操作說明主題Clocks How-to Topics 包含在您的應用程式中使用 Clock 物件的程式碼範例。Contains code examples for using the Clock object in your application.
主要畫面格操作說明主題Key-Frame How-to Topics 包含在應用程式中使用主要畫面格動畫的程式碼範例。Contains code examples for using key-frame animations in your application.
路徑動畫操作說明主題Path Animation How-to Topics 包含在應用程式中使用路徑動畫的程式碼範例。Contains code examples for using path animations in your application.

參考資料Reference