Información general sobre animaciones From/To/By

En este tema se describe cómo usar animaciones From/To/By para animar propiedades de dependencia. Una animación From/To/By crea una transición entre dos valores.

Requisitos previos

Para comprender este tema, debería estar familiarizado con las características de las animaciones de WPF. Consulte Información general sobre animaciones para una introducción a las características de las animaciones.

¿Qué es una animación From/To/By?

Una animación From/To/By es un tipo de AnimationTimeline que crea una transición entre un valor inicial y un valor final. El tiempo que tarda la transición en completarse se determina por la propiedad Duration de dicha animación.

Puede aplicar una animación From/To/By a una propiedad mediante Storyboard en marcado y en código, o mediante el método BeginAnimation en código. También puede usar una animación From/To/By para crear un objeto AnimationClock y aplicarlo a una o más propiedades. Para más información sobre los distintos métodos para aplicar animaciones, consulte la Información general sobre técnicas de animación de propiedades.

Las animaciones From/To/By no pueden tener más de dos valores de destino. Si necesita una animación que tenga más de dos valores de destino, use una animación de fotogramas clave. Las animaciones de fotogramas clave se describen en Información general sobre animaciones de fotogramas clave.

Tipos de animaciones From/To/By

Dado que las animaciones generan valores de propiedad, existen distintos tipos de animaciones para los diversos tipos de propiedades. Para animar una propiedad que toma un elemento Double, como la propiedad Width de un elemento, use una animación que produzca valores Double. Para animar una propiedad que toma un elemento Point, use una animación que produzca valores Point, y así sucesivamente.

Las clases de animación From/To/By pertenecen al espacio de nombres System.Windows.Media.Animation y cumplen con la siguiente convención de nomenclatura:

<Type>Animation

Donde <Type> es el tipo de valor que la clase anima.

WPF proporciona las siguientes clases de animación From/To/By.

Tipo de propiedad Clase de animación From/To/By correspondiente
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

Una animación From/To/By crea una transición entre dos valores de destino. Es común especificar un valor inicial (establecido por la propiedad From) y un valor final (establecido por la propiedad To). Pero también se puede especificar solo un valor inicial, un valor de destino o un valor de desplazamiento. En estos casos, la animación obtiene el valor de destino que falta de la propiedad que se anima. La lista siguiente describe las diferentes maneras de especificar los valores de destino de una animación.

  • Valor inicial

    Use la propiedad From cuando quiera especificar de forma explícita el valor inicial de la animación. Puede usar la propiedad From por sí misma o con la propiedad To o By. Si solo especifica la propiedad From, la animación realiza la transición desde ese valor hasta el valor base de la propiedad animada.

  • Valor final

    Para especificar el valor final de una animación, use la propiedad To. Si usa la propiedad To por sí sola, la animación obtiene su valor inicial de la propiedad que se anima o de la salida de otra animación que se aplica a la misma propiedad. Puede usar la propiedad To junto con la propiedad From para especificar de forma explícita los valores inicial y final de la animación.

  • Valor de desplazamiento

    La propiedad By le permite especificar un desplazamiento en lugar del valor inicial o final explícito de la animación. La propiedad By de una animación especifica en qué medida la animación cambia un valor a lo largo de su duración. Puede usar la propiedad By por sí misma o con la propiedad From. Si solo especifica la propiedad By, la animación suma el valor de desplazamiento al valor base de la propiedad o a la salida de otra animación.

Usar valores From/To/By

En las secciones siguientes se describe cómo usar las propiedades From, To y By juntas o por separado.

En cada uno de los ejemplos de esta sección se usa DoubleAnimation, que es un tipo de animación From/To/By, para animar la propiedad Width de una clase Rectangle que mide 10 píxeles independientes del dispositivo de alto y 100 de ancho.

Aunque en cada ejemplo se use una clase DoubleAnimation, las propiedades From, To y By de todas las animaciones From/To/By se comportan exactamente igual. Aunque en cada uno de estos ejemplos se use una clase Storyboard, puede usar las animaciones From/To/By de otras maneras. Para más información, consulte Información general sobre técnicas de animación de propiedades.

De/Para

Al establecer los valores From y To juntos, la animación progresa del valor especificado por la propiedad From al valor especificado por la propiedad To.

En el ejemplo siguiente se establece la propiedad From de DoubleAnimation en 50 y su propiedad To en 300. Como resultado, la propiedad Width de Rectangle se anima 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)

En

Cuando solo se establece la propiedad To, la animación progresa desde el valor base de la propiedad animada o desde la salida de una animación en composición que se aplicó anteriormente a la misma propiedad, hasta el valor que especifique la propiedad To.

("Composición de animación" hace referencia a una animación Active o Filling que se ha aplicado anteriormente a la misma propiedad que todavía está activa cuando se aplica la animación actual mediante el comportamiento de entrega Compose).

En el ejemplo siguiente se establece la propiedad To de DoubleAnimation en 300. Como no se especificó ningún valor inicial, DoubleAnimation usa el valor base (100) de la propiedad Width como su valor inicial. Width de Rectangle se anima desde 100 hasta el valor de destino de 300 de la animación.

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

Cuando solo se establece la propiedad By, la animación progresa desde el valor base de la propiedad animada o desde la salida de una animación en composición que se aplicó anteriormente a la misma propiedad, hasta el valor que especifique la propiedad By.

En el ejemplo siguiente se establece la propiedad By de DoubleAnimation en 300. Como en el ejemplo no se especifica un valor inicial, DoubleAnimation usa el valor base de la propiedad Width, 100, como valor inicial. El valor final se determina al añadir el valor By de la animación, 300, a su valor inicial, 100: 400. Como resultado, la propiedad Width de Rectangle se anima 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)

From/By

Al establecer las propiedades From y By de una animación, la animación progresa desde el valor especificado por la propiedad From hasta el valor especificado por la suma de las propiedades From y By.

En el ejemplo siguiente se establece la propiedad From de DoubleAnimation en 50 y su propiedad By en 300. El valor final se determina al añadir el valor By de la animación, 300, a su valor inicial, 50: 350. Como resultado, la propiedad Width de Rectangle se anima 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

Cuando solo se establece la propiedad From, la animación progresa desde el valor que especifica la propiedad From hasta el valor base de la propiedad animada o la salida de una animación en composición.

En el ejemplo siguiente se establece la propiedad From de DoubleAnimation en 50. Como no se especificó ningún valor final, DoubleAnimation usa el valor base de la propiedad Width, 100, como su valor final. Width de Rectangle se anima desde 50 hasta el valor base de la propiedad Width, 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)

To/By

Si establece las propiedades To y By de una animación, se omite la propiedad By.

Otros tipos de animación

Las animaciones From/To/By no son el único tipo de animaciones que WPF proporciona: también ofrece animaciones de fotogramas clave y animaciones de trazado.

WPF también le permite crear sus propios tipos de animaciones personalizadas. Para más información, consulte Información general sobre animaciones personalizadas.

Vea también