動畫概觀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.

之前WPFWPFMicrosoft WindowsMicrosoft Windows開發人員,就必須建立並管理他們自己的計時系統或使用特殊的自訂程式庫。Prior to WPFWPF, Microsoft WindowsMicrosoft 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)和已完全整合至WPFWPFframework。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. 例如,若要讓架構元素變大,您以動畫顯示其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值,以動畫顯示Opacity屬性RectangleIt 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.

下圖顯示如何建立Rectangle中的項目StackPanel在 XAML 中。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>

下圖顯示如何建立Rectangle中的項目StackPanel在程式碼中。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. ADoubleAnimation是一個這類動畫。A DoubleAnimation is one such animation. ADoubleAnimation建立兩個雙精度浮點數值之間的轉換。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.00.0您設定其From屬性設1.0及其To屬性設0.0To 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. 下圖顯示如何建立DoubleAnimation在 XAML 中。The following shows how to create a DoubleAnimation in XAML.

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

    下圖顯示如何建立DoubleAnimation在程式碼中。The 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. 下圖顯示如何設定Duration為 XAML 中的五秒。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為程式碼中的五秒。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.00.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屬性的動畫trueTo make the element fade back into view after it vanishes, set the AutoReverse property of the animation to true. 若要讓動畫無限期地重複,設定其RepeatBehavior屬性設ForeverTo make the animation repeat indefinitely, set its RepeatBehavior property to Forever. 下圖顯示如何設定AutoReverseRepeatBehaviorXAML 中的屬性。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. 下圖顯示如何建立Storyboard在 XAML 中。The 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. 下圖顯示如何設定的目標名稱DoubleAnimationMyRectangle在 XAML 中。The 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>
    

    下圖顯示如何設定的目標名稱DoubleAnimationMyRectangle在程式碼中。The 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. 下列範例示範如何設定動畫目標Opacity屬性Rectangle在 XAML 中。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>
    

    下列範例示範如何設定動畫目標Opacity屬性Rectangle在程式碼中。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

最簡單的方式套用並開始StoryboardXAMLXAML是使用事件觸發程序。The easiest way to apply and start a Storyboard in XAMLXAML is to use an event trigger. 本節說明如何建立關聯Storyboard以在 XAML 中的觸發程序。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. ABeginStoryboard是一種TriggerAction會套用並開始StoryboardA 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. 設定RoutedEvent的屬性EventTrigger您想要啟動的路由事件StoryboardSet 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. 新增EventTriggerTriggers矩形的集合。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

    稱為 "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. 在 by 動畫概觀 > 中詳細說明 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

    抽象類別,當您實作時,建立動畫<型別> 值。Abstract class that, when you implement it, animates a <Type> value. 此類別可做為基底類別<型別> 動畫並<型別> 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. 否則,請使用<型別> 動畫或主要畫面格<型別> 動畫。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 建立動畫ColorSolidColorBrushGradientStopAnimate the Color of a SolidColorBrush or a GradientStop.
Double DoubleAnimation DoubleAnimationUsingKeyFrames DoubleAnimationUsingPath 建立動畫WidthDockPanelHeightButtonAnimate the Width of a DockPanel or the Height of a Button.
Point PointAnimation PointAnimationUsingKeyFrames PointAnimationUsingPath 建立動畫Center位置EllipseGeometryAnimate the Center position of an EllipseGeometry.
String NoneNone StringAnimationUsingKeyFrames None 建立動畫TextTextBlockContentButtonAnimate 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. ATimeline定義一段時間。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.

三個常用的計時屬性是DurationAutoReverse,和RepeatBehaviorThree 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.

下列語法顯示的簡化的版本Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML)屬性語法Duration屬性。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 : secondshours : 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,然後宣告 newDuration結構在使用該TimeSpanOne 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屬性會指定是否之後結束的時間軸播放回溯其DurationThe 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. AStoryboard容器時間軸,提供其包含之動畫的目標資訊。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.

  • 若要讓Freezable物件成為動畫目標,在XAMLXAML,您使用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,其關聯EventTriggerTo 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,或使用Begin方法Storyboard類別。To start a Storyboard in code, you can use an EventTrigger or use the Begin method of the Storyboard class.

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

先前範例所示範如何啟動Storyboard事件發生時。The 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. 根據預設,啟動時間軸Filling結束時。By default, a timeline starts Filling when it ends. 動畫是Filling保有最終輸出值。An animation that is Filling holds its final output value.

DoubleAnimation在上述範例中並不會結束因為其RepeatBehavior屬性設定為ForeverThe 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方法並指定 nullAnimationTimeline參數。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

大部分的動畫屬性可以是資料繫結或以動畫顯示;例如,您可以建立動畫Duration屬性DoubleAnimationMost 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.

示範如何以動畫顯示上一節中的範例,請參閱Opacity的矩形。Refer 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並將其套用至的物件和所指定的屬性TargetNameTargetPropertyDoubleAnimationThe 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. 在此情況下,計時系統會套用至時鐘Opacity屬性之物件的名稱為"MyRectangle"。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. 其目的是要控制它的子系時鐘,針對所建立的時鐘DoubleAnimationIts 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 主題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