动画概述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. 例如,若要使框架元素增长,请对其和属性进行动画处理 Width HeightFor example, to make a framework element grow, you animate its Width and Height properties. 若要使对象从视图中淡化,请对其属性进行动画处理 OpacityTo 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包含许多具有属性的对象 IAnimatablecontains 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 在 XAML 中创建一个元素 StackPanelThe 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

使元素淡入和淡出的一种方法是对其属性进行动画处理 OpacityOne 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. 下面演示了如何 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.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. 下面的示例演示如何 AutoReverse RepeatBehavior 在 XAML 中设置和属性。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"/>
    

    下面演示了如何 AutoReverse RepeatBehavior 在代码中设置和属性。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. 下面演示了如何 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 中将动画配置为面向 Opacity 的属性 RectangleThe 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 代码中的的属性为目标 RectangleThe 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

若要应用和启动中,最简单的方法 Storyboard XAMLXAML 是使用事件触发器。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. BeginStoryboardTriggerAction 应用和启动的类型 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 使用生成值的动画 DoubleTo 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.AnimationBecause 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>动画<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.

  • <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> 动画和 <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> 动画或关键帧 <Type> 动画。Otherwise, use a <Type>Animation or KeyFrame<Type>Animation.

在大多数情况下,你将需要使用 <Type> 动画类,如 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 对或的进行动画处理 Color SolidColorBrush GradientStopAnimate the Color of a SolidColorBrush or a GradientStop.
Double DoubleAnimation DoubleAnimationUsingKeyFrames DoubleAnimationUsingPath 对的或的进行动画处理 Width DockPanel Height ButtonAnimate 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 NoneNone 对的或的进行动画处理 Text TextBlock Content ButtonAnimate 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. 动画还会在输出值通过其指定时间段(或)时进行计算 DurationAn 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 ,通常通过使用值来指定 TimeSpanThe 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.

下面的语法显示了属性的简化版本的 可扩展应用程序标记语言 (XAML)Extensible Application Markup Language (XAML) Duration 属性语法。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 ,然后使用声明新的 Duration 结构 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 值和完整语法的详细信息 可扩展应用程序标记语言 (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属性指定时间线在到达其末尾后是否向后播放 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. Storyboard是为其所包含的动画提供目标信息的容器时间线A Storyboard is a container timeline that provides targeting information for the animations it contains.

以对象和属性为目标Targeting Objects and Properties

Storyboard类提供 TargetName TargetProperty 属性和附加属性。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 对象指定名称 FreezableAssigning 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 动画目标,请通过设置其属性为其指定一个名称 NameTo 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.

下面的部分提供了在和代码中命名元素的示例 XAMLXAMLThe 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 方法 StoryboardTo 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. 还可以在启动后以交互方式控制 a 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. 与前面的示例不同, RepeatBehavior AutoReverse 此动画的和属性将保留其默认值。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 方法并为参数指定 null AnimationTimelineOne 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.

请注意,虽然设置具有或动画的属性值 Active Filling 似乎不起作用,但属性值确实会更改。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 ,并将其应用于由和指定的对象和属性 TargetName TargetProperty DoubleAnimationThe 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. 若要使动画反映更改,请使用或方法重新应用它的情节提要 BeginStoryboard BeginTo 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