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

Este tópico descreve como usar animações de/para/por para animar propriedades de dependência. Uma animação de/para/por cria uma transição entre dois valores.

Pré-requisitos

Para entender este tópico, você deve estar familiarizado com os recursos de animações do WPF. Para obter uma introdução aos recursos de animações, consulte a Visão geral da animação.

O que é uma animação de/para/por?

Uma animação De/Para/Por é um tipo de AnimationTimeline que cria uma transição entre um valor inicial e um valor final. A quantidade de tempo que a transição leva para ser concluída é determinada pela Duration animação.

Você pode aplicar uma animação De/Para/Por a uma propriedade usando uma Storyboard marcação in e código, ou usando o BeginAnimation método em código. Você também pode usar uma animação De/Para/Por para criar uma e aplicá-la a uma AnimationClock ou mais propriedades. Para obter mais informações sobre os diferentes métodos para aplicação de animações, consulte a Visão geral das técnicas de animação de propriedades.

Animações de/para/por podem ter não mais do que dois valores de destino. Se você precisar de uma animação que tem mais de dois valores de destino, use uma animação de quadro-chave. Animações de quadro chave são descritas na Visão geral das animações de quadro chave.

Tipos de animação de/para/por

Como as animações geram valores de propriedade, existem diferentes tipos de animação para diferentes tipos de propriedades. Para animar uma propriedade que usa um , como a Width propriedade de um Doubleelemento, use uma animação que produza Double valores. Para animar uma propriedade que usa um Point, use uma animação que produz Point valores e assim por diante.

As classes de animação De/Para/Por pertencem ao System.Windows.Media.Animation namespace e usam a seguinte convenção de nomenclatura:

<Tipo>Animation

Onde <Type> é o tipo de valor que a classe anima.

O WPF fornece as seguintes classes de animação De/Para/Por.

Tipo de propriedade Classe de animação De/Para/Por correspondente
Byte ByteAnimation
Color ColorAnimation
Decimal DecimalAnimation
Double DoubleAnimation
Int16 Int16Animation
Int32 Int32Animation
Int64 Int64Animation
Point PointAnimation
Quaternion QuaternionAnimation
Rect RectAnimation
Rotation3D Rotation3DAnimation
Single SingleAnimation
Size SizeAnimation
Thickness ThicknessAnimation
Vector3D Vector3DAnimation
Vector VectorAnimation

Valores de destino

Uma animação de/para/por cria uma transição entre dois valores de destino. É comum especificar um valor inicial (defini-lo usando a propriedade) e um valor final (defini-lo usando a FromTo propriedade). No entanto, você também pode especificar apenas um valor inicial, um valor de destino ou um valor de deslocamento. Nesses casos, a animação obtém o valor de destino ausente da propriedade que está sendo animada. A lista a seguir descreve as diferentes maneiras de especificar os valores de destino de uma animação.

  • Valor inicial

    Use a From propriedade quando desejar especificar explicitamente o valor inicial de uma animação. Você pode usar a propriedade por si só, ou com a FromTo propriedade ou By . Se você especificar apenas a propriedade, a animação fará a From transição desse valor para o valor base da propriedade animada.

  • Valor final

    Para especificar um valor final de uma animação, use sua To propriedade. Se você usar a propriedade por si só, a To animação obterá seu valor inicial da propriedade que está sendo animada ou da saída de outra animação que é aplicada à mesma propriedade. Você pode usar a propriedade junto com a ToFrom propriedade para especificar explicitamente os valores inicial e final da animação.

  • Valor de deslocamento

    A By propriedade permite especificar um deslocamento em vez de um valor inicial ou final explícito para a animação. A By propriedade de uma animação especifica o quanto a animação altera um valor ao longo de sua duração. Você pode usar a propriedade sozinho ou com a ByFrom propriedade. Se você especificar apenas a propriedade, a By animação adicionará o valor de deslocamento ao valor base da propriedade ou à saída de outra animação.

Usando valores de/para/por

As seções a seguir descrevem como usar as Frompropriedades , Toe By juntas ou separadamente.

Os exemplos nesta seção usam um , que é um tipo de animação De/Para/Por, para animar a Width propriedade de um DoubleAnimationRectangle que tem 10 pixels independentes de dispositivo de altura e 100 pixels independentes de dispositivo de largura.

Embora cada exemplo use um DoubleAnimation, as propriedades De, Para e Por de todas as animações De/Para/Por se comportam de forma idêntica. Embora cada um desses exemplos use um Storyboard, você pode usar animações De/Para/Por de outras maneiras. Para obter mais informações, consulte a Visão geral das técnicas de animação de propriedade.

De/para

Quando você define os From valores e To juntos, a animação progride do valor especificado pela propriedade para o valor especificado pela FromTo propriedade.

O exemplo a seguir define a From propriedade do DoubleAnimation como 50 e sua To propriedade como 300. Como resultado, o WidthRectangle do é animado de 50 a 300.

// Demonstrates the From and To properties used together.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "fromToAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.Black;

// Demonstrates the From and To properties used together.
// Animates the rectangle's Width property from 50 to 300 over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 50;
myDoubleAnimation.To = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "fromToAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the From and To properties used together.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("fromToAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.Black

' Demonstrates the From and To properties used together.
' Animates the rectangle's Width property from 50 to 300 over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.From = 50
myDoubleAnimation.To = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "fromToAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

To

Quando você define apenas a propriedade, a To animação progride do valor base da propriedade animada ou da saída de uma animação de composição que foi aplicada anteriormente à mesma propriedade, para o valor especificado pela To propriedade.

("Composição de animação" refere-se a uma Active animação ou animação Filling que anteriormente se aplicava à mesma propriedade que ainda está em vigor quando a animação atual foi aplicada usando o comportamento de Compose transferência.)

O exemplo a seguir define apenas a To propriedade de o DoubleAnimation como 300. Como nenhum valor inicial foi especificado, o DoubleAnimation usa o valor base (100) da Width propriedade como seu valor inicial. O Width do Rectangle é animado de 100 para o valor alvo da animação de 300.

// Demonstrates the use of the To property.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "toAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.Gray;

// Demonstrates the To property used by itself. Animates
// the Rectangle's Width property from its base value
// (100) to 300 over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.To = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "toAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the To property.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("toAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.Gray

' Demonstrates the To property used by itself. Animates
' the Rectangle's Width property from its base value
' (100) to 300 over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.To = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "toAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

Por

Quando você define apenas a propriedade de uma animação, a animação progride do valor base da propriedade que está sendo animada ou da saída de uma animação de composição para a By soma desse valor e o valor especificado pela By propriedade.

O exemplo a seguir define apenas a By propriedade de o DoubleAnimation como 300. Como o exemplo não especifica um valor inicial, o DoubleAnimation usa o Width valor base da propriedade, 100, como seu valor inicial. O valor final é determinado adicionando o By valor da animação, 300, ao seu valor inicial, 100: 400. Como resultado, o WidthRectangle do é animado de 100 a 400.

// Demonstrates the use of the By property.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "byAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.RoyalBlue;

// Demonstrates the By property used by itself.
// Increments the Rectangle's Width property by 300 over 10 seconds.
// As a result, the Width property is animated from its base value
// (100) to 400 (100 + 300) over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.By = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the By property.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("byAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.RoyalBlue

' Demonstrates the By property used by itself.
' Increments the Rectangle's Width property by 300 over 10 seconds.
' As a result, the Width property is animated from its base value
' (100) to 400 (100 + 300) over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.By = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

De/por

Quando você define as From propriedades e By de uma animação, a animação progride do valor especificado pela propriedade para o valor especificado pela From soma das From propriedades e By .

O exemplo a seguir define a From propriedade do DoubleAnimation como 50 e sua By propriedade como 300. O valor final é determinado adicionando o By valor da animação, 300, ao seu valor inicial, 50: 350. Como resultado, o WidthRectangle do é animado de 50 a 350.

// Demonstrates the use of the From and By properties.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "byAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.BlueViolet;

// Demonstrates the From and By properties used together.
// Increments the Rectangle's Width property by 300 over 10 seconds.
// As a result, the Width property is animated from 50
// to 350 (50 + 300) over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 50;
myDoubleAnimation.By = 300;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the From and By properties.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("byAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.BlueViolet

' Demonstrates the From and By properties used together.
' Increments the Rectangle's Width property by 300 over 10 seconds.
' As a result, the Width property is animated from 50
' to 350 (50 + 300) over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.From = 50
myDoubleAnimation.By = 300
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "byAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

De

Quando você especifica apenas o valor de uma animação, a animação progride do valor especificado pela From propriedade, para o From valor base da propriedade que está sendo animada ou para a saída de uma animação de composição.

O exemplo a seguir define apenas a From propriedade de o DoubleAnimation como 50. Como nenhum valor final foi especificado, o DoubleAnimation usa o Width valor base da propriedade, 100, como seu valor final. O Width do é animado de 50 para o valor base do RectangleWidth imóvel, 100.

// Demonstrates the use of the From property.

// Create a NameScope for this page so that
// Storyboards can be used.
NameScope.SetNameScope(this, new NameScope());

Rectangle myRectangle = new Rectangle();

// Assign the Rectangle a name so that
// it can be targeted by a Storyboard.
this.RegisterName(
    "fromAnimatedRectangle", myRectangle);
myRectangle.Height = 10;
myRectangle.Width = 100;
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.Fill = Brushes.Purple;

// Demonstrates the From property used by itself. Animates the
// rectangle's Width property from 50 to its base value (100)
// over 10 seconds.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 50;
myDoubleAnimation.Duration =
    new Duration(TimeSpan.FromSeconds(10));

Storyboard.SetTargetName(myDoubleAnimation, "fromAnimatedRectangle");
Storyboard.SetTargetProperty(myDoubleAnimation,
    new PropertyPath(Rectangle.WidthProperty));
Storyboard myStoryboard = new Storyboard();
myStoryboard.Children.Add(myDoubleAnimation);

// Use an anonymous event handler to begin the animation
// when the rectangle is clicked.
myRectangle.MouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs args)
    {
        myStoryboard.Begin(myRectangle);
    };
' Demonstrates the use of the From property.

' Create a NameScope for this page so that
' Storyboards can be used.
NameScope.SetNameScope(Me, New NameScope())

Dim myRectangle As New Rectangle()

' Assign the Rectangle a name so that
' it can be targeted by a Storyboard.
Me.RegisterName("fromAnimatedRectangle", myRectangle)
myRectangle.Height = 10
myRectangle.Width = 100
myRectangle.HorizontalAlignment = HorizontalAlignment.Left
myRectangle.Fill = Brushes.Purple

' Demonstrates the From property used by itself. Animates the
' rectangle's Width property from 50 to its base value (100)
' over 10 seconds.
Dim myDoubleAnimation As New DoubleAnimation()
myDoubleAnimation.From = 50
myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(10))

Storyboard.SetTargetName(myDoubleAnimation, "fromAnimatedRectangle")
Storyboard.SetTargetProperty(myDoubleAnimation, New PropertyPath(Rectangle.WidthProperty))
Dim myStoryboard As New Storyboard()
myStoryboard.Children.Add(myDoubleAnimation)

' Use an anonymous event handler to begin the animation
' when the rectangle is clicked.
AddHandler myRectangle.MouseLeftButtonDown, Sub(sender As Object, args As MouseButtonEventArgs) myStoryboard.Begin(myRectangle)

Para/por

Se você definir as propriedades e as ToBy de uma animação, a By propriedade será ignorada.

Outros tipos de animação

As animações De/Para/Por não são o único tipo de animação que o WPF fornece: ele também fornece animações de quadro-chave e animações de caminho.

O WPF também permite que você crie seus próprios tipos de animação personalizados. Para obter mais informações, consulte o visão geral de animações personalizadas.

Confira também