Share via


Revisão de Animação

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. Animando uma cor de plano de fundo ou aplicando um animado de apenas Transform, você pode criar transições de tela drástica ou fornecer indicações visual útil.

This overview provides an introduction to the WPF animation and timing system. It focuses on the animation of WPF objects by using storyboards.

Este tópico contém as seguintes seções.

  • Introducing Animations
  • WPF Property Animation System
  • Exemplo: Verifique a atenuar um elemento, dentro e fora do modo de exibição
  • Animation Types
  • Applying an Animation to a Property
  • Interactively Control a Storyboard
  • What Happens After an Animation Ends?
  • Data Binding and Animating Animations
  • Other Ways to Animate
  • Animation Samples
  • Related Topics
  • Reference

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.

Antes WPF, Microsoft Windows os desenvolvedores tinham que criar e gerenciar seus próprios sistemas de temporização ou usam especial bibliotecas personalizadas. WPFinclui um sistema eficiente de temporização que é exposto por meio de código gerenciado e Extensible Application Markup Language (XAML) e que está profundamente integrado a WPF framework. WPF animação torna fácil animar controles e outros objetos gráficos.

WPFmanipula todo o trabalho de fundo de gerenciamento de um sistema de temporização e redesenho de tela com eficiência. Ele fornece classes de tempo que permitem focalizar os efeitos que você deseja criar, em vez da mecânica de atingir esses efeitos. WPFtambém torna mais fácil para criar suas próprias animações, expondo a partir do qual as classes podem herdar de classes base animação, produzir animações personalizadas. These custom animations gain many of the performance benefits of the standard animation classes.

WPF Property Animation System

If you understand a few important concepts about the timing system, WPF animations can be easier to use. Most important is that, in WPF, you animate objects by applying animation to their individual properties. Por exemplo, para tornar um elemento de estrutura de crescer, animar sua Width e Height Propriedades. Para tornar um objeto desaparecer do modo de exibição, você anima sua Opacity propriedade.

For a property to have animation capabilities, it must meet the following three requirements:

WPFcontém muitos objetos que tenham IAnimatable Propriedades. Controles como Button e TabControle também Panel e Shape objetos herdam DependencyObject. Most of their properties are dependency properties.

You can use animations almost anywhere, which includes in styles and control templates. Animações não precisam ser visual; Você pode animar objetos que não fazem parte da interface do usuário se eles atendem aos critérios descritos nesta seção.

Exemplo: Verifique a atenuar um elemento, dentro e fora do modo de exibição

Este exemplo mostra como usar um WPF a animação para animar o valor de uma propriedade de dependência. It uses a DoubleAnimation, which is a type of animation that generates Double values, to animate the Opacity property of a Rectangle. As a result, the Rectangle fades in and out of view.

A primeira parte do exemplo cria um Rectangle elemento. The steps that follow show how to create an animation and apply it to the rectangle's Opacity property.

A seguir mostra como criar um Rectangle elemento em um StackPanel em XAML.

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

A seguir mostra como criar um Rectangle elemento em um StackPanel no código.

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

Dim myRectangle As Rectangle = 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
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;
myPanel.Children.Add(myRectangle);
this.Content = myPanel;

Parte 1: Criar um DoubleAnimation.

One way to make an element fade in and out of view is to animate its Opacity property. Because the Opacity property is of type Double, you need an animation that produces double values. A DoubleAnimation is one such animation. A DoubleAnimation creates a transition between two double values. To specify its starting value, you set its From property. To specify its ending value, you set its To property.

  1. An opacity value of 1.0 makes the object completely opaque, and an opacity value of 0.0 makes it completely invisible. To make the animation transition from 1.0 to 0.0 you set its From property to 1.0 and its To property to 0.0. A seguir mostra como criar um DoubleAnimation em XAML.

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

    A seguir mostra como criar um DoubleAnimation no código.

    Dim myDoubleAnimation As DoubleAnimation = New DoubleAnimation()
    myDoubleAnimation.From = 1.0
    myDoubleAnimation.To = 0.0
    
    DoubleAnimation myDoubleAnimation = new DoubleAnimation();
    myDoubleAnimation.From = 1.0;
    myDoubleAnimation.To = 0.0;
    
  2. Next, you must specify a Duration. The Duration of an animation specifies how long it takes to go from its starting value to its destination value. A seguir mostra como definir o Duration a cinco segundos no XAML.

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

    A seguir mostra como definir o Duration a cinco segundos no código.

    myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(5))
    
    myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));
    
  3. 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. To make the element fade back into view after it vanishes, set the AutoReverse property of the animation to true. Para repetir a animação indefinidamente, defina sua RepeatBehavior propriedade para Forever.A seguir mostra como definir o AutoReverse e RepeatBehavior Propriedades em XAML.

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

    A seguir mostra como definir o AutoReverse e RepeatBehavior Propriedades no código.

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

Parte 2: Criar um Storyboard

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. Create the Storyboard and add the animation as its child. A seguir mostra como criar o Storyboard no XAML.

    Para criar o Storyboard no código, declare uma Storyboard variável no nível da classe.

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

    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. The Storyboard has to know where to apply the animation. Use the Storyboard.TargetName attached property to specify the object to animate. A seguir mostra como definir o nome do destino da DoubleAnimation para MyRectangle em XAML.

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

    A seguir mostra como definir o nome do destino da DoubleAnimation para MyRectangle no código.

    Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name)
    
    Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name);
    
  3. Use the TargetProperty attached property to specify the property to animate. A seguir mostra como a animação está configurada para o destino a Opacity propriedade da Rectangle em XAML.

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

    A seguir mostra como a animação está configurada para o destino a Opacity propriedade da Rectangle no código.

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

For more information about TargetProperty syntax and for additional examples, see the Visão geral sobre Storyboards.

Parte 3 (XAML): Associar o Storyboard de um disparador

The easiest way to apply and start a Storyboard in XAML is to use an event trigger. Esta seção mostra como associar a Storyboard com um disparador no XAML.

  1. Create a BeginStoryboard object and associate your storyboard with it. 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. Create an EventTrigger and add the BeginStoryboard to its Actions collection. 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 Visão geral sobre eventos roteados.)

    <!-- 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. Adicionar o EventTrigger para o Triggers a coleção do retângulo.

    <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>
    

Parte 3 (código): Associar um manipulador de eventos Storyboard

The easiest way to apply and start a Storyboard in code is to use an event handler. Esta seção mostra como associar a Storyboard com um manipulador de eventos no código.

  1. Register for the Loaded event of the rectangle.

    AddHandler myRectangle.Loaded, AddressOf myRectangleLoaded
    
    myRectangle.Loaded += new RoutedEventHandler(myRectangleLoaded);
    
  2. Declare the event handler. In the event handler, use the Begin method to apply the storyboard.

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

Complete Example

A seguir mostra como criar um retângulo de fade e saia do modo de exibição em XAML.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://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>

A seguir mostra como criar um retângulo de fade e saia do modo de exibição no código.

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
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);
        }
    }
}

Animation Types

Because animations generate property values, different animation types exist for different property types. To animate a property that takes a Double, such as the Width property of an element, use an animation that produces Double values. To animate a property that takes a Point, use an animation that produces Point values, and so on. 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:

  • <tipo de> animação

    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.

    • To specify a starting value, set the From property of the animation.

    • To specify an ending value, set the To property of the animation.

    • 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 animations are described in detail in the Visão geral sobre animações de/para/por.

  • <tipo de> AnimationUsingKeyFrames

    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 Visão geral de animações de Quadro-Chave.

  • <tipo de> AnimationUsingPath

    Path animations enable you to use a geometric path in order to produce animated values.

  • <tipo de> AnimationBase

    Abstract class that, when you implement it, animates a <Type> value. 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.

In 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

Corresponding basic (From/To/By) animation

Corresponding key frame animation

Corresponding Path Animation

Usage example

Color

ColorAnimation

ColorAnimationUsingKeyFrames

None

Animate the Color of a SolidColorBrush or a GradientStop.

Double

DoubleAnimation

DoubleAnimationUsingKeyFrames

DoubleAnimationUsingPath

Animate the Width of a DockPanel or the Height of a Button.

Point

PointAnimation

PointAnimationUsingKeyFrames

PointAnimationUsingPath

Animate the Center position of an EllipseGeometry.

String

None

StringAnimationUsingKeyFrames

None

Animate the Text of a TextBlock or the Content of a Button.

Animations Are Timelines

All the animation types inherit from the Timeline class; therefore, all animations are specialized types of timelines. A Timeline defines a segment of time. Você pode especificar o os comportamentos de temporização de uma linha do tempo: sua Duration, quantas vezes é repetido e até mesmo tempo como rápido progride para o proprietário.

Because an animation is a Timeline, it also represents a segment of time. An animation also calculates output values as it progresses though its specified segment of time (or Duration). As the animation progresses, or "plays," it updates the property that it is associated with.

Three frequently used timing properties are Duration, AutoReverse, and RepeatBehavior.

The Duration Property

As previously mentioned, a timeline represents a segment of time. 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.

An animation uses its Duration property to determine its current value. If you do not specify a Duration value for an animation, it uses 1 second, which is the default.

The following syntax shows a simplified version of the Extensible Application Markup Language (XAML) attribute syntax for the Duration property.

horas:minutos:segundos

The following table shows several Duration settings and their resulting values.

Setting

Resulting value

0:0:5.5

5.5 seconds.

0:30:5.5

30 minutes and 5.5 seconds.

1:30:5.5

1 hour, 30 minutes, and 5.5 seconds.

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.

Para obter mais informações sobre Duration valores e a completa Extensible Application Markup Language (XAML) sintaxe, consulte o Duration estrutura.

AutoReverse

The AutoReverse property specifies whether a timeline plays backward after it reaches the end of its 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. By default, this property is false.

RepeatBehavior

The RepeatBehavior property specifies how many times a timeline plays. 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 Visão geral sobre comportamentos de temporização.

Applying an Animation to a Property

The previous sections describe the different types of animations and their timing properties. Esta seção mostra como aplicar a animação para a propriedade que você deseja animar. Storyboardobjetos fornecem uma maneira de aplicar as animações às propriedades. A Storyboard is a container timeline that provides targeting information for the animations it contains.

Targeting Objects and Properties

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.

Assigning a name to a FrameworkElement differs from assigning a name to a Freezable object. Most controls and panels are framework elements; however, most purely graphical objects, such as brushes, transforms, and geometries, are freezable objects. Se você não tiver certeza se um tipo é um FrameworkElement ou um Freezable, consulte a A hierarquia de herança seção de sua documentação de referência.

  • To make a FrameworkElement an animation target, you give it a name by setting its Name property. In code, you must also use the RegisterName method to register the element name with the page to which it belongs.

  • Para fazer uma Freezable uma animação do objeto de destino XAML, você pode usar o x: nome de diretiva para atribuir a ele um nome. No código, você simplesmente usar o RegisterName método para registrar o objeto com a página à qual ele pertence.

The sections that follow provide an example of naming an element in XAML and code. Para obter informações mais detalhadas sobre nomeação e direcionamento, consulte o Visão geral sobre Storyboards.

Applying and Starting Storyboards

To start a storyboard in XAML, you associate it with an EventTrigger. An EventTrigger is an object that describes what actions to take when a specified event occurs. 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. Unlike event handlers, event triggers can be fully described in XAML; no other code is required.

To start a Storyboard in code, you can use an EventTrigger or use the Begin method of the Storyboard class.

Interactively Control a Storyboard

The previous example showed how to start a Storyboard when an event occurs. Você pode controlar também interativamente um Storyboard após ele ser iniciado: Você pode pausar, continuar, parar, avançá-lo para o seu período de preenchimento, busca e remover o Storyboard. For more information and an example that shows how to interactively control a Storyboard, see the Visão geral sobre Storyboards.

What Happens After an Animation Ends?

The FillBehavior property specifies how a timeline behaves when it ends. By default, a timeline starts Filling when it ends. An animation that is Filling holds its final output value.

The DoubleAnimation in the previous example does not end because its RepeatBehavior property is set to Forever. The following example animates a rectangle by using a similar animation. Unlike the previous example, the RepeatBehavior and AutoReverse properties of this animation are left at their default values. 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>
            Dim myDoubleAnimation As New DoubleAnimation()
            myDoubleAnimation.From = 1.0
            myDoubleAnimation.To = 0.0
            myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(5))
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 1.0;
myDoubleAnimation.To = 0.0;
myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(5));

Because its FillBehavior was not changed from its default value, which is HoldEnd, the animation holds it final value, 0, when it ends. Therefore, the Opacity of the rectangle remains at 0 after the animation ends. 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.

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 Como: Definir uma Propriedade Após Animá-la com um Storyboard.

Note that, although setting a property value that has an Active or Filling animation appears to have no effect, the property value does change. Para obter mais informações, consulte o Visão Geral de Animação e Sistema de Tempo.

Data Binding and Animating Animations

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.

Refer to the example in the previous section that showed how to animate the Opacity of a rectangle. When the rectangle in the previous example is loaded, its event trigger applies the Storyboard. The timing system creates a copy of the Storyboard and its animation. 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.

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. In this case, the timing system applies the clock to the Opacity property of the object that is named "MyRectangle."

Although a clock is also created for the Storyboard, the clock is not applied to any properties. 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. 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. In code, you can use the Seek method to shift the storyboard back to its previous position.

Para obter um exemplo de dados vinculada a animação, consulte Amostra de animação de Spline chave. For more information about how the animation and timing system works, see Visão Geral de Animação e Sistema de Tempo.

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. Para obter mais informações, consulte o Visão geral de técnicas de animação de propriedades.

Animation Samples

The following samples can help you start adding animation to your applications.

Title

Description

Visão Geral de Animação e Sistema de Tempo

Descreve como o sistema de temporização utiliza o Timeline e Clock classes, que permite que você criar animações.

Dicas e truques de animação

Dicas úteis para solucionar problemas de animações, como o desempenho.

Visão Geral de Animações Personalizadas

Descreve como estender o sistema de animação com quadros-chave, classes de animação ou retornos de chamada por quadro.

Visão geral sobre animações de/para/por

Descreve como criar uma animação que faz a transição entre dois valores.

Visão geral de animações de Quadro-Chave

Descreve como criar uma animação com vários valores de destino, incluindo a capacidade de controlar o método de interpolação.

Funções de atenuação

Explica como aplicar as animações para obter o comportamento realista, tais como saltando fórmulas matemáticas.

Visão Geral de Animações de Caminho

Descreve como mover ou girar um objeto ao longo de um demarcador complexo.

Visão geral de técnicas de animação de propriedades

Descreve as animações de propriedade usando storyboards, animações de locais, relógios e animações por quadro.

Visão geral sobre Storyboards

Descreve como usar o storyboards com vários cronogramas para criar animações complexas.

Visão geral sobre comportamentos de temporização

Descreve o Timeline tipos e as propriedades usadas em animações.

Visão geral Eventos de Temporizadores

Descreve os eventos disponíveis sobre o Timeline e Clock objetos para a execução de código em pontos do tempo, tais como iniciar, pausar, continuar, ignorar ou parar.

Tópicos de "Como Fazer" de animação e tempo

Contém exemplos de código para usar os cronogramas e animações no seu aplicativo.

Tópicos de Como Fazer em Clocks

Contém exemplos de código para usar o Clock o objeto em seu aplicativo.

Key-Frame Animation How-to Topics

Contém exemplos de código para usar animações quadro-chave no seu aplicativo.

Tópicos de Como Fazer em Animação de Caminho

Contém exemplos de código para usar animações de caminho no seu aplicativo.

Reference

Timeline

Storyboard

BeginStoryboard

Clock

Histórico de alterações

Date

History

Motivo

Outubro de 2010

Adicionado trechos de Visual Basic ausentes.

Comentários do cliente.