Vue d'ensemble des techniques d'animation de propriétés

Cette rubrique décrit les différentes approches pour animer des propriétés : tables de montage séquentiel, animations locales, horloges et animations par image.

Prérequis

Pour comprendre cette rubrique, vous devez connaître les fonctionnalités de base utilisées pour l’animation, décrites dans Vue d’ensemble de l’animation.

Différentes méthodes d’animation

Étant donné qu’il existe de nombreux scénarios différents pour l’animation des propriétés, WPF fournit plusieurs approches pour l’animation des propriétés.

Pour chaque approche, le tableau suivant indique s’il peut être utilisé par instance, dans les styles, dans les modèles de contrôle ou dans les modèles de données ; s’il peut être utilisé en XAML ; et si l’approche vous permet de contrôler de manière interactive l’animation. « Par instance » fait référence à la technique consistant à appliquer une animation ou une table de montage séquentiel directement aux instances d’un objet, plutôt qu’à un style, un modèle de contrôle ou un modèle de données.

Technique d’animation Scénarios Prend en charge XAML Contrôlable de manière interactive
Animation de table de montage séquentiel Par instance, , Style, ControlTemplateDataTemplate Oui Oui
Animation locale Par instance No No
Animation horloge Par instance Non Oui
Animation par image Par instance Non N/A

Animations de table de montage séquentiel

Utilisez un Storyboard moment où vous souhaitez définir et appliquer vos animations en XAML, contrôler de manière interactive vos animations après leur démarrage, créer une arborescence complexe d’animations ou animer dans un Style, ControlTemplate ou DataTemplate. Pour qu’un objet soit animé par un Storyboardobjet , il doit être un FrameworkElement ou FrameworkContentElement, ou il doit être utilisé pour définir un FrameworkElement ou FrameworkContentElement. Pour plus d’informations, consultez l’article Vue d’ensemble des tables de montage séquentiel.

Il Storyboard s’agit d’un type spécial de conteneur Timeline qui fournit des informations de ciblage pour les animations qu’il contient. Pour animer avec un Storyboard, vous effectuez les trois étapes suivantes.

  1. Déclarez une Storyboard ou plusieurs animations.

  2. Utilisez les TargetName propriétés et TargetProperty les propriétés jointes pour spécifier l’objet cible et la propriété de chaque animation.

  3. (Code uniquement) Définir un NameScope pour un FrameworkElement ou FrameworkContentElement. Inscrivez les noms des objets à animer avec ce FrameworkElement ou FrameworkContentElement.

  4. Commencez le Storyboard.

Le début d’une Storyboard animation s’applique aux propriétés qu’ils animent et les démarrent. Il existe deux façons de commencer un Storyboard: vous pouvez utiliser la Begin méthode fournie par la Storyboard classe, ou vous pouvez utiliser une BeginStoryboard action. La seule façon d’animer en XAML consiste à utiliser une BeginStoryboard action. Une BeginStoryboard action peut être utilisée dans une EventTriggerpropriété , Triggerou un DataTrigger.

Le tableau suivant présente les différents endroits où chaque Storyboard technique de début est prise en charge : par instance, style, modèle de contrôle et modèle de données.

La table de montage séquentiel démarre à l’aide de… Par instance Style Modèle de contrôle Modèle de données Exemple
BeginStoryboard et un EventTrigger Oui Oui Oui Oui Animer une propriété à l’aide d’une table de montage séquentiel
BeginStoryboard et une propriété Trigger Non Oui Oui Oui Déclencher une animation en cas de modification d’une valeur de propriété
BeginStoryboard et un DataTrigger Non Oui Oui Oui Comment : déclencher une animation en cas de modification de données
Méthode Begin Oui Non Non No Animer une propriété à l’aide d’une table de montage séquentiel

Pour plus d’informations sur les objets, consultez la vue d’ensemble Storyboarddes storyboards.

Animations locales

Les animations locales offrent un moyen pratique d’animer une propriété de dépendance d’un Animatable objet. Utilisez les animations locales lorsque vous souhaitez appliquer une seule animation à une propriété et quand vous n’avez pas besoin de contrôler de manière interactive l’animation après son démarrage. Contrairement à une Storyboard animation, une animation locale peut animer un objet qui n’est pas associé à un FrameworkElement ou un FrameworkContentElement. Vous n’avez pas non plus besoin de définir un NameScope pour ce type d’animation.

Les animations locales peuvent uniquement être utilisées dans le code et ne peuvent pas être définies dans des styles, modèles de contrôle ou modèles de données. Une animation locale ne peut pas être contrôlée de façon interactive après son démarrage.

Pour animer à l’aide d’une animation locale, procédez comme suit.

  1. Créez un objet AnimationTimeline.

  2. Utilisez la BeginAnimation méthode de l’objet que vous souhaitez animer pour appliquer la AnimationTimeline propriété que vous spécifiez.

L’exemple suivant montre comment animer la largeur et la couleur d’arrière-plan d’un Button.

/*

   This sample demonstrates how to apply non-storyboard animations to a property.
   To animate in markup, you must use storyboards.

*/

using namespace System;
using namespace System::Windows;
using namespace System::Windows::Navigation;
using namespace System::Windows::Media;
using namespace System::Windows::Media::Animation;
using namespace System::Windows::Shapes;
using namespace System::Windows::Controls;


namespace Microsoft {
   namespace Samples {
      namespace Animation {
         namespace LocalAnimations {
            // Create the demonstration.
            public ref class LocalAnimationExample : Page {

            public: 
               LocalAnimationExample ()
               {
                  WindowTitle = "Local Animation Example";
                  StackPanel^ myStackPanel = gcnew StackPanel();
                  myStackPanel->Margin = Thickness(20);

                  // Create and set the Button.
                  Button^ aButton = gcnew Button();
                  aButton->Content = "A Button";

                  // Animate the Button's Width.
                  DoubleAnimation^ myDoubleAnimation = gcnew DoubleAnimation();
                  myDoubleAnimation->From = 75;
                  myDoubleAnimation->To = 300;
                  myDoubleAnimation->Duration = Duration(TimeSpan::FromSeconds(5));
                  myDoubleAnimation->AutoReverse = true;
                  myDoubleAnimation->RepeatBehavior = RepeatBehavior::Forever;

                  // Apply the animation to the button's Width property.
                  aButton->BeginAnimation(Button::WidthProperty, myDoubleAnimation);

                  // Create and animate a Brush to set the button's Background.
                  SolidColorBrush^ myBrush = gcnew SolidColorBrush();
                  myBrush->Color = Colors::Blue;

                  ColorAnimation^ myColorAnimation = gcnew ColorAnimation();
                  myColorAnimation->From = Colors::Blue;
                  myColorAnimation->To = Colors::Red;
                  myColorAnimation->Duration = Duration(TimeSpan::FromMilliseconds(7000));
                  myColorAnimation->AutoReverse = true;
                  myColorAnimation->RepeatBehavior = RepeatBehavior::Forever;

                  // Apply the animation to the brush's Color property.
                  myBrush->BeginAnimation(SolidColorBrush::ColorProperty, myColorAnimation);
                  aButton->Background = myBrush;

                  // Add the Button to the panel.
                  myStackPanel->Children->Add(aButton);
                  this->Content = myStackPanel;
               };
            };
         }
      }
   }
}
/*

   This sample demonstrates how to apply non-storyboard animations to a property.
   To animate in markup, you must use storyboards.

*/

using System;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls;

namespace Microsoft.Samples.Animation.LocalAnimations
{

    // Create the demonstration.
    public class LocalAnimationExample : Page
    {

        public LocalAnimationExample()
        {

            WindowTitle = "Local Animation Example";
            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Margin = new Thickness(20);

            // Create and set the Button.
            Button aButton = new Button();
            aButton.Content = "A Button";

            // Animate the Button's Width.
            DoubleAnimation myDoubleAnimation = new DoubleAnimation();
            myDoubleAnimation.From = 75;
            myDoubleAnimation.To = 300;
            myDoubleAnimation.Duration =  new Duration(TimeSpan.FromSeconds(5));
            myDoubleAnimation.AutoReverse = true;
            myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever;

            // Apply the animation to the button's Width property.
            aButton.BeginAnimation(Button.WidthProperty, myDoubleAnimation);

            // Create and animate a Brush to set the button's Background.
            SolidColorBrush myBrush = new SolidColorBrush();
            myBrush.Color = Colors.Blue;

            ColorAnimation myColorAnimation = new ColorAnimation();
            myColorAnimation.From = Colors.Blue;
            myColorAnimation.To = Colors.Red;
            myColorAnimation.Duration =  new Duration(TimeSpan.FromMilliseconds(7000));
            myColorAnimation.AutoReverse = true;
            myColorAnimation.RepeatBehavior = RepeatBehavior.Forever;

            // Apply the animation to the brush's Color property.
            myBrush.BeginAnimation(SolidColorBrush.ColorProperty, myColorAnimation);
            aButton.Background = myBrush;

            // Add the Button to the panel.
            myStackPanel.Children.Add(aButton);
            this.Content = myStackPanel;
        }
    }
}
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''This sample demonstrates how to apply non-storyboard animations to a property.
'''To animate in markup, you must use storyboards.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Imports System.Windows
Imports System.Windows.Navigation
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes
Imports System.Windows.Controls

Namespace Microsoft.Samples.Animation.LocalAnimations

    ' Create the demonstration.
    Public Class LocalAnimationExample
        Inherits Page

        Public Sub New()

            WindowTitle = "Animate Property Example"
            Dim myStackPanel As New StackPanel()
            myStackPanel.Margin = New Thickness(20)

            ' Create and set the Button.
            Dim aButton As New Button()
            aButton.Content = "A Button"

            ' Animate the Button's Width.
            Dim myDoubleAnimation As New DoubleAnimation()
            myDoubleAnimation.From = 75
            myDoubleAnimation.To = 300
            myDoubleAnimation.Duration = New Duration(TimeSpan.FromSeconds(5))
            myDoubleAnimation.AutoReverse = True
            myDoubleAnimation.RepeatBehavior = RepeatBehavior.Forever

            ' Apply the animation to the button's Width property.
            aButton.BeginAnimation(Button.WidthProperty, myDoubleAnimation)

            ' Create and animate a Brush to set the button's Background.
            Dim myBrush As New SolidColorBrush()
            myBrush.Color = Colors.Blue

            Dim myColorAnimation As New ColorAnimation()
            myColorAnimation.From = Colors.Blue
            myColorAnimation.To = Colors.Red
            myColorAnimation.Duration = New Duration(TimeSpan.FromMilliseconds(7000))
            myColorAnimation.AutoReverse = True
            myColorAnimation.RepeatBehavior = RepeatBehavior.Forever

            ' Apply the animation to the brush's Color property.
            myBrush.BeginAnimation(SolidColorBrush.ColorProperty, myColorAnimation)
            aButton.Background = myBrush

            ' Add the Button to the panel.
            myStackPanel.Children.Add(aButton)
            Me.Content = myStackPanel
        End Sub
    End Class
End Namespace

Animation horloge

Utilisez des Clock objets lorsque vous souhaitez animer sans utiliser d’arborescences Storyboard de minutage complexes ou contrôler de manière interactive les animations après leur démarrage. Vous pouvez utiliser des objets Clock pour animer une propriété de dépendance de n’importe quel Animatable objet.

Vous ne pouvez pas utiliser Clock d’objets directement pour animer des styles, des modèles de contrôle ou des modèles de données. (Le système d’animation et de minutage utilise réellement des Clock objets pour animer dans des styles, des modèles de contrôle et des modèles de données, mais il doit créer ces Clock objets pour vous à partir d’un Storyboard. Pour plus d’informations sur la relation entre Storyboard les objets et Clock les objets, consultez la vue d’ensemble du système d’animation et de minutage.)

Pour appliquer un seul Clock à une propriété, effectuez les étapes suivantes.

  1. Créez un objet AnimationTimeline.

  2. Utilisez la CreateClock méthode de création AnimationTimeline d’un AnimationClock.

  3. Utilisez la ApplyAnimationClock méthode de l’objet que vous souhaitez animer pour appliquer la AnimationClock propriété que vous spécifiez.

L’exemple suivant montre comment créer et AnimationClock l’appliquer à deux propriétés similaires.

/*
    This example shows how to create and apply
    an AnimationClock.
*/

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Media.Animation;

namespace Microsoft.Samples.Animation.TimingBehaviors
{
    public class AnimationClockExample : Page
    {

        ScaleTransform myScaleTransform;

        public AnimationClockExample()
        {

            this.WindowTitle = "Opacity Animation Example";
            this.Background = Brushes.White;
            StackPanel myStackPanel = new StackPanel();
            myStackPanel.Margin = new Thickness(20);

            // Create a button that with a ScaleTransform.
            // The ScaleTransform will animate when the
            // button is clicked.
            Button myButton = new Button();
            myButton.Margin = new Thickness(50);
            myButton.HorizontalAlignment = HorizontalAlignment.Left;
            myButton.Content = "Click Me";
            myScaleTransform = new ScaleTransform(1,1);
            myButton.RenderTransform = myScaleTransform;

            // Associate an event handler with the
            // button's Click event.
            myButton.Click += new RoutedEventHandler(myButton_Clicked);

            myStackPanel.Children.Add(myButton);
            this.Content = myStackPanel;
        }

        // Create and apply and animation when the button is clicked.
        private void myButton_Clicked(object sender, RoutedEventArgs e)
        {

            // Create a DoubleAnimation to animate the
            // ScaleTransform.
            DoubleAnimation myAnimation =
                new DoubleAnimation(
                    1, // "From" value
                    5, // "To" value
                    new Duration(TimeSpan.FromSeconds(5))
                );
            myAnimation.AutoReverse = true;

            // Create a clock the for the animation.
            AnimationClock myClock = myAnimation.CreateClock();

            // Associate the clock the ScaleX and
            // ScaleY properties of the button's
            // ScaleTransform.
            myScaleTransform.ApplyAnimationClock(
                ScaleTransform.ScaleXProperty, myClock);
            myScaleTransform.ApplyAnimationClock(
                ScaleTransform.ScaleYProperty, myClock);
        }
    }
}
'
'    This example shows how to create and apply
'    an AnimationClock.
'


Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Imports System.Windows.Shapes
Imports System.Windows.Media.Animation


Namespace Microsoft.Samples.Animation.TimingBehaviors
    Public Class AnimationClockExample
        Inherits Page

        Private ReadOnly myScaleTransform As ScaleTransform

        Public Sub New()

            WindowTitle = "Opacity Animation Example"
            Background = Brushes.White
            Dim myStackPanel As New StackPanel With {
                .Margin = New Thickness(20)
            }

                ' Create a button that with a ScaleTransform.
                ' The ScaleTransform will animate when the
                ' button is clicked.
            Dim myButton As New Button With {
                .Margin = New Thickness(50),
                .HorizontalAlignment = HorizontalAlignment.Left,
                .Content = "Click Me"
            }
            myScaleTransform = New ScaleTransform(1,1)
            myButton.RenderTransform = myScaleTransform


            ' Associate an event handler with the
            ' button's Click event.
            AddHandler myButton.Click, AddressOf myButton_Clicked

            myStackPanel.Children.Add(myButton)
            Content = myStackPanel
        End Sub

        ' Create and apply and animation when the button is clicked.
        Private Sub myButton_Clicked(sender As Object, e As RoutedEventArgs)

            ' Create a DoubleAnimation to animate the
            ' ScaleTransform.
            Dim myAnimation As New DoubleAnimation(1, 5, New Duration(TimeSpan.FromSeconds(5))) With {
                .AutoReverse = True
            } ' "To" value -  "From" value

            ' Create a clock the for the animation.
            Dim myClock As AnimationClock = myAnimation.CreateClock()

            ' Associate the clock the ScaleX and
            ' ScaleY properties of the button's
            ' ScaleTransform.
            myScaleTransform.ApplyAnimationClock(ScaleTransform.ScaleXProperty, myClock)
            myScaleTransform.ApplyAnimationClock(ScaleTransform.ScaleYProperty, myClock)
        End Sub
    End Class
End Namespace

Pour créer une arborescence de minutage et l’utiliser pour animer des propriétés, effectuez les étapes suivantes.

  1. Utilisez et AnimationTimeline objets ParallelTimeline pour créer l’arborescence de minutage.

  2. Utilisez la CreateClock racine ParallelTimeline pour créer un ClockGroup.

  3. Effectuez une itération au sein Children de l’objet ClockGroup enfant et appliquez ses objets enfants Clock . Pour chaque AnimationClock enfant, utilisez la ApplyAnimationClock méthode de l’objet que vous souhaitez animer pour appliquer la AnimationClock propriété que vous spécifiez

Pour plus d’informations sur les objets Clock, consultez Vue d’ensemble de l’animation et du système de minutage.

Animation par image : ignorer le système d’animation et de minutage

Utilisez cette approche lorsque vous devez contourner complètement le système d’animation WPF. Un scénario pour cette approche est l’animation physique, où pour chaque étape de l’animation les objets doivent être traités une nouvelle fois en fonction du dernier jeu d’interactions d’objet.

Les animations par image ne peuvent pas être définies dans des styles, modèles de contrôle ou modèles de données.

Pour animer frame-by-frame, vous inscrivez l’événement Rendering de l’objet qui contient les objets que vous souhaitez animer. Cette méthode de gestionnaire d’événements est appelée une fois par image. Chaque fois que WPF marshale les données de rendu persistantes dans l’arborescence visuelle sur l’arborescence de composition, votre méthode de gestionnaire d’événements est appelée.

Dans votre gestionnaire d’événements, effectuez les calculs nécessaires pour votre effet d’animation et définissez les propriétés des objets à animer avec ces valeurs.

Pour obtenir l’heure de présentation de l’image actuelle, l’événement EventArgs associé peut être casté en tant RenderingEventArgsque RenderingTime propriété que vous pouvez utiliser pour obtenir l’heure de rendu de l’image actuelle.

Pour plus d’informations, consultez la Rendering page.

Voir aussi