动画概述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 包括通过托管代码公开的有效计时系统,并 可扩展应用程序标记语言 (XAML)Extensible Application Markup Language (XAML) 并深度集成到 WPFWPF 框架中。includes an efficient timing system that is exposed through managed code and 可扩展应用程序标记语言 (XAML)Extensible Application Markup Language (XAML) and that is deeply integrated into the WPFWPF framework. 通过使用 WPFWPF 动画,可以轻松地对控件和其他图形对象进行动画处理。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 通过公开动画基类(你使用的类可以继承这些类)可以轻松创建自己的动画,这样便可以制作自定义动画。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 对象从 DependencyObject继承。Controls 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.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. 下面演示了如何在 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 设置为五秒。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 属性设置为 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. 下面演示了如何在 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. 下面演示了如何在 XAML 中将 DoubleAnimation 的目标名称设置为 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. 本部分说明如何将 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. 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

    这些动画称为“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 动画概述中进行了详细说明。From/To/By animations are described in detail in the From/To/By Animations Overview.

  • <类型> 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.

  • <类型> AnimationUsingPath<Type>AnimationUsingPath

    路径动画支持使用几何路径来生成动画值。Path animations enable you to use a geometric path in order to produce animated values.

  • <类型> 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 SolidColorBrushGradientStopColor 进行动画处理。Animate the Color of a SolidColorBrush or a GradientStop.
Double DoubleAnimation DoubleAnimationUsingKeyFrames DoubleAnimationUsingPath DockPanelWidthButtonHeight 进行动画处理。Animate 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 TextBlockTextButtonContent 进行动画处理。Animate 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 属性的 可扩展应用程序标记语言 (XAML)Extensible Application Markup Language (XAML) 特性语法的简化版本。The following syntax shows a simplified version of the 可扩展应用程序标记语言 (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 值和完整 可扩展应用程序标记语言 (XAML)Extensible Application Markup Language (XAML) 语法的详细信息,请参阅 Duration 结构。For more information about Duration values and the complete 可扩展应用程序标记语言 (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. 如果您不确定某个类型是 FrameworkElement 还是 Freezable,请参阅其参考文档的 "继承层次结构" 部分。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中启动情节提要,请将其与 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. 默认情况下,时间线在结束时 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 方法,并为 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.

请参阅上一节中的示例,该示例演示如何对矩形的 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 创建一个时钟,并将其应用于 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.

TitleTitle 描述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 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 介绍 Timeline 上可用的事件,以及在时间线中执行代码的 Clock 对象,如开始、暂停、继续、跳过或停止。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