Cenni preliminari sulle tecniche di animazione delle proprietà

Questo argomento descrive i diversi metodi di animazione delle proprietà: storyboard, animazioni locali, orologi e animazioni per fotogramma.

Prerequisiti

Per comprendere questo argomento, è necessario conoscere le funzionalità di base delle animazioni descritte nella sezione Cenni preliminari sull'animazione.

Diversi modi per aggiungere un'animazione

Poiché esistono molti scenari diversi per l'animazione delle proprietà, WPF offre diversi approcci per l'animazione delle proprietà.

Per ogni approccio, la tabella seguente indica se può essere usata per ogni istanza, negli stili, nei modelli di controllo o nei modelli di dati; se può essere usato in XAML; e se l'approccio consente di controllare in modo interattivo l'animazione. "Per istanza" si riferisce alla tecnica di applicazione di un'animazione o uno storyboard direttamente a istanze di un oggetto, piuttosto che in uno stile, un modello di controllo o un modello di dati.

Tecnica di animazione Scenari Supporta XAML Controllabile in modo interattivo
Animazione storyboard Per istanza, Style, ControlTemplate, DataTemplate
Animazione locale Per istanza No No
Animazione orologio Per istanza No
Animazione per fotogramma Per istanza No N/D

Animazioni storyboard

Usa un oggetto Storyboard quando vuoi definire e applicare le animazioni in XAML, controlla in modo interattivo le animazioni dopo l'avvio, crea un albero complesso di animazioni o anima in un StyleControlTemplate oggetto o DataTemplate. Affinché un oggetto venga animato da un Storyboardoggetto , deve essere un FrameworkElement oggetto o FrameworkContentElementoppure deve essere utilizzato per impostare un FrameworkElement oggetto o FrameworkContentElement. Per altri dettagli, vedere Cenni preliminari sugli storyboard.

Un Storyboard è un tipo speciale di contenitore Timeline che fornisce informazioni di destinazione per le animazioni contenute. Per aggiungere un'animazione a , Storyboardcompletare i tre passaggi seguenti.

  1. Dichiarare un Storyboard oggetto e una o più animazioni.

  2. Utilizzare le TargetName proprietà associate e TargetProperty per specificare l'oggetto di destinazione e la proprietà di ogni animazione.

  3. (Solo codice) Definire un NameScope oggetto per un FrameworkElement oggetto o FrameworkContentElement. Registrare i nomi degli oggetti da animare con tale FrameworkElement oggetto o FrameworkContentElement.

  4. Iniziare l'oggetto Storyboard.

L'inizio di un Storyboard oggetto applica animazioni alle proprietà che animano e le avvia. Esistono due modi per iniziare un oggetto Storyboard: è possibile usare il Begin metodo fornito dalla Storyboard classe oppure è possibile usare un'azione BeginStoryboard . L'unico modo per animare in XAML consiste nell'usare un'azione BeginStoryboard . Un'azione BeginStoryboard può essere usata in una EventTriggerproprietà Trigger, o in un oggetto DataTrigger.

La tabella seguente illustra le diverse posizioni in cui ogni Storyboard tecnica di inizio è supportata: per istanza, stile, modello di controllo e modello di dati.

Storyboard iniziato usando… Per istanza Style Modello del controllo Modello di dati Esempio
BeginStoryboard e un EventTrigger Animare una proprietà utilizzando uno storyboard
BeginStoryboard e una proprietà Trigger No Attivare un'animazione quando il valore di una proprietà viene modificato
BeginStoryboard e un DataTrigger No Procedura: Attivare un'animazione quando i dati vengono modificati
Metodo Begin No No No Animare una proprietà utilizzando uno storyboard

Per altre informazioni sugli oggetti, vedere Cenni preliminari sugli Storyboard storyboard.

Animazioni locali

Le animazioni locali offrono un modo pratico per animare una proprietà di dipendenza di qualsiasi Animatable oggetto. Usare le animazioni locali per applicare una singola animazione a una proprietà, senza bisogno di controllare in modo interattivo l'animazione dopo l'avvio. A differenza di un'animazioneStoryboard, un'animazione locale può animare un oggetto che non è associato a un FrameworkElement oggetto o a .FrameworkContentElement Non è inoltre necessario definire un NameScope oggetto per questo tipo di animazione.

Le animazioni locali possono essere usate solo nel codice e non possono essere definite negli stili, nei modelli di controllo o nei modelli di dati. Un'animazione locale non può essere controllata in modo interattivo dopo l'avvio.

Per aggiungere un'animazione usando un'animazione locale, completare i passaggi seguenti.

  1. Creare un oggetto AnimationTimeline.

  2. Utilizzare il BeginAnimation metodo dell'oggetto da animare per applicare l'oggetto AnimationTimeline alla proprietà specificata.

Nell'esempio seguente viene illustrato come animare la larghezza e il colore di sfondo di un oggetto 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

Animazioni orologio

Usa Clock gli oggetti quando vuoi animare senza usare un Storyboard oggetto e vuoi creare alberi di intervallo complessi o animazioni di controllo interattivo dopo l'avvio. È possibile utilizzare oggetti Clock per animare una proprietà di dipendenza di qualsiasi Animatable oggetto.

Non è possibile utilizzare Clock oggetti direttamente per animare gli stili, i modelli di controllo o i modelli di dati. Il sistema di animazione e temporizzazione usa Clock effettivamente oggetti per animare stili, modelli di controllo e modelli di dati, ma deve creare tali Clock oggetti automaticamente da un oggetto Storyboard. Per altre informazioni sulla relazione tra Storyboard oggetti e Clock oggetti, vedere Cenni preliminari sul sistema di animazione e intervallo.

Per applicare un singolo Clock oggetto a una proprietà, completare la procedura seguente.

  1. Creare un oggetto AnimationTimeline.

  2. Utilizzare il CreateClock metodo di AnimationTimeline per creare un oggetto AnimationClock.

  3. Utilizzare il ApplyAnimationClock metodo dell'oggetto da animare per applicare l'oggetto AnimationClock alla proprietà specificata.

Nell'esempio seguente viene illustrato come creare un oggetto e applicarlo AnimationClock a due proprietà simili.

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

Per creare un albero di temporizzazione e usarne le proprietà animate, completare i passaggi seguenti.

  1. Utilizzare ParallelTimeline oggetti e AnimationTimeline per creare l'albero di temporizzazione.

  2. Usare l'oggetto CreateClock della radice ParallelTimeline per creare un oggetto ClockGroup.

  3. Scorrere l'oggetto ChildrenClockGroup di e applicare i relativi oggetti figlio Clock . Per ogni AnimationClock elemento figlio, utilizzare il ApplyAnimationClock metodo dell'oggetto da animare per applicare l'oggetto AnimationClock alla proprietà specificata

Per altre informazioni sugli oggetti Clock, vedere Cenni preliminari sull'animazione e sul sistema di temporizzazione.

Animazione per fotogramma: ignorare il sistema di animazione e di temporizzazione

Usare questo approccio quando è necessario ignorare completamente il sistema di animazione WPF. Uno scenario di questo approccio è rappresentato dalle animazioni fisiche, dove ciascun passaggio dell'animazione richiede che gli oggetti siano ricalcolati in base all'ultima serie di interazioni dell'oggetto.

Le animazioni per fotogramma non possono essere definite negli stili, nei modelli di controllo o nei modelli di dati.

Per animare frame per fotogramma, si registra per l'evento Rendering dell'oggetto che contiene gli oggetti da animare. Questo metodo del gestore eventi viene chiamato una volta per ogni fotogramma. Ogni volta che WPF effettua il marshalling dei dati di rendering persistenti nella struttura ad albero visuale nell'albero di composizione, viene chiamato il metodo del gestore eventi.

Nel gestore eventi eseguire i calcoli necessari per l'effetto di animazione e impostare le proprietà degli oggetti cui si desidera aggiungere un'animazione con tali valori.

Per ottenere l'ora di presentazione per il frame corrente, è possibile eseguire il cast dell'oggetto EventArgs associato a questo evento come RenderingEventArgs, che fornisce una RenderingTime proprietà che è possibile usare per ottenere l'ora di rendering del frame corrente.

Per altre informazioni, vedere la Rendering pagina.

Vedi anche