Share via


Información general sobre animaciones From/To/By

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

Este tema contiene las secciones siguientes.

Requisitos previos

Para entender este tema, debe estar familiarizado con las características de animación básicas de WPF. Para obtener una introducción a las características de animación, vea Información general sobre animaciones.

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

Una animación From/To/By es un tipo de clase AnimationTimeline que crea una transición entre un valor inicial y un valor final. La propiedad Duration de una animación determina la cantidad de tiempo que tarda en completarse esa animación.

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

Las animaciones From/To/By pueden tener un máximo 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 propiedades, hay distintos tipos de animaciones para los diversos tipos de propiedades. Para animar una propiedad que acepta un valor Double, como la propiedad Width de un elemento, se usa una animación que genera valores Double. Para animar una propiedad que acepta una estructura Point, se usa una animación que genera valores Point, y así sucesivamente.

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

*<Tipo>*Animation

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

WPF proporciona las siguientes clases de animaciones From/To/By.

Tipo de propiedad

Clase de animaciones 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 (que se establece mediante la propiedad From) y un valor final (que se establece mediante la propiedad To). Sin embargo, también puede especificarse sólo 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. En la lista siguiente se describen las distintas maneras de especificar los valores de destino de una animación.

  • Valor inicial

    Use la propiedad From cuando desee especificar explícitamente el valor inicial de una animación. Puede usar la propiedad From por sí sola o con la propiedad To o By. Si especifica únicamente 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 el valor inicial de la propiedad que se anima o de la salida de otra animación que se aplique a la misma propiedad. Puede usar la propiedad To junto con la propiedad From para especificar explícitamente los valores inicial y final de la animación.

  • Valor de desplazamiento

    La propiedad By permite especificar un desplazamiento en lugar de un valor explícito inicial o final para la animación. La propiedad By de una animación especifica en qué medida cambiará el valor de una animación mientras se realiza. Puede usar la propiedad By por sí sola o con la propiedad From. Si especifica únicamente la propiedad By, la animación agrega el valor de desplazamiento al valor base de la propiedad o a la salida de otra animación.

Usar los 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 utiliza un DoubleAnimation, que es un tipo de animación From/To/By, para animar la propiedad Width de un Rectangle con 10 píxeles independientes del dispositivo de alto y 100 píxeles independientes del dispositivo de ancho.

Aunque cada ejemplo usa 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 usa Storyboard, las animaciones From/To/By pueden usarse de otras maneras. Para obtener más información, vea Información general sobre técnicas de animación de propiedades.

From/To

Cuando se establecen los valores de From y To conjuntamente, la animación progresa desde el valor especificado por la propiedad From hasta el valor especificado por la propiedad To.

En el ejemplo siguiente se establece la propiedad From del objeto DoubleAnimation en 50 y su propiedad To en 300. Como resultado, la propiedad Width de Rectangle se anima desde 50 hasta 300.

            ' 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)
// 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. -->
<Rectangle Name="fromToAnimatedRectangle"
   Height="10" Width="100" HorizontalAlignment="Left"
   Fill="Black">
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
      <BeginStoryboard>
        <Storyboard>
        <!-- Demonstrates the From and To properties used together.
               Animates the rectangle's Width property from 50 to 300 over 10 seconds. -->
        <DoubleAnimation 
          Storyboard.TargetName="fromToAnimatedRectangle" 
          Storyboard.TargetProperty="Width"
          From="50" To="300" Duration="0:0:10" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

Para

Cuando sólo 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 compuesta que se aplicó previamente a la misma propiedad, hasta el valor especificado por la propiedad To.

("Animación compuesta" hace referencia a una animación Active o Filling que se aplicó previamente a la misma propiedad y que sigue en vigor al aplicar la animación actual mediante el comportamiento de entrega Compose.)

En el ejemplo siguiente se establece únicamente la propiedad To del objeto DoubleAnimation en 300. Dado que no se especifica ningún valor inicial, DoubleAnimation usa el valor base (100) de la propiedad Width como valor inicial. La propiedad Width de Rectangle se anima desde 100 hasta el valor de destino de la animación, que es 300.

            ' 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)
// 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. -->
<Rectangle Name="toAnimatedRectangle"
   Height="10" Width="100" HorizontalAlignment="Left"
   Fill="Gray">
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
      <BeginStoryboard>
        <Storyboard>

          <!-- Demonstrates the To property used by itself.
               Animates the Rectangle's Width property from its base value
               (100) to 300 over 10 seconds. -->
          <DoubleAnimation 
            Storyboard.TargetName="toAnimatedRectangle" 
            Storyboard.TargetProperty="Width"
            To="300" Duration="0:0:10" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

By

Cuando sólo se establece la propiedad By de una animación, esta última progresa desde el valor base de la propiedad animada, o desde la salida de una animación compuesta, hasta la suma de ese valor y del valor especificado por la propiedad By.

En el ejemplo siguiente se establece únicamente la propiedad By del objeto DoubleAnimation en 300. Dado que 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 sumando el valor de By de la animación, 300, y su valor inicial, 100, lo que da 400. Como resultado, la propiedad Width de Rectangle se anima desde 100 hasta 400.

            ' 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)
// 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. -->
<Rectangle Name="byAnimatedRectangle" 
   Height="10" Width="100" HorizontalAlignment="Left"
   Fill="RoyalBlue">
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
      <BeginStoryboard>
        <Storyboard>

          <!-- 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 
            Storyboard.TargetName="byAnimatedRectangle" 
            Storyboard.TargetProperty="Width" 
            By="300" Duration="0:0:10" />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

From/By

Cuando se establecen las propiedades From y By de una animación, esta última progresa desde 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 del objeto DoubleAnimation en 50 y su propiedad By en 300. El valor final se determina sumando el valor de By de la animación, 300, y su valor inicial, 50, lo que da 350. Como resultado, la propiedad Width de Rectangle se anima desde 50 hasta 350.

            ' 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)
// 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. -->
<Rectangle Name="fromByAnimatedRectangle" Grid.Row="6" Grid.Column="2"
   Height="10" Width="100" HorizontalAlignment="Left"
   Fill="BlueViolet">
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
      <BeginStoryboard>
        <Storyboard>

          <!-- Demonstrates the From and By properties used by 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 
            Storyboard.TargetName="fromByAnimatedRectangle" 
            Storyboard.TargetProperty="Width" 
            From="50" By="300" Duration="0:0:10"  />

        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

From

Cuando se especifica únicamente el valor de la propiedad From de una animación, esta última progresa desde el valor especificado por la propiedad From hasta el valor base de la propiedad animada o hasta la salida de una animación compuesta.

En el ejemplo siguiente se establece únicamente la propiedad From del objeto DoubleAnimation en 50. Dado que no se especifica ningún valor final, DoubleAnimation usa el valor base de la propiedad Width, 100, como valor final. La propiedad 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(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)
// 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. -->
<Rectangle Name="fromAnimatedRectangle" Grid.Row="8" Grid.Column="2"
   Height="10" Width="100" HorizontalAlignment="Left" 
   Fill="Purple">
  <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.MouseLeftButtonDown">
      <BeginStoryboard>
        <Storyboard>
          <!-- Demonstrates the From property used by itself.
               Animates the rectangle's Width property from 50 to its base value (100)
               over 10 seconds. -->
          <DoubleAnimation 
            Storyboard.TargetName="fromAnimatedRectangle" 
            Storyboard.TargetProperty="Width"
            From="50" Duration="0:0:10"  />
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </Rectangle.Triggers>
</Rectangle>

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 animación que WPF proporciona: también proporciona animaciones de fotogramas clave y de trayectoria.

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

Vea también

Referencia

Timeline

Storyboard

Conceptos

Información general sobre animaciones

Información general sobre objetos Storyboard

Información general sobre animaciones de fotogramas clave

Información general sobre animaciones en trazados

Información general sobre animaciones personalizadas

Otros recursos

Ejemplo From, To, and By Animation Target Values