Практическое руководство. Установка длительности анимации

Timeline представляет сегмент времени, а длина этого сегмента определяется свойством Duration временной шкалы. Когда Timeline достигает окончания своей длительности, воспроизведение прекращается. Если у Timeline есть дочерние временные шкалы, их воспроизведение также останавливается. Для анимации свойство Duration определяет, какое время требуется для перехода анимации от начального значения к конечному значению.

Можно указать Duration с определенным, конечным временем или специальными значениями Automatic или.Forever Длительность анимации всегда должна определяться значением времени, так как анимация всегда должна иметь определенную конечную длину. В противном случае анимация не сможет переходить между своими целевыми значениями. У временных шкал контейнера (объектов: TimelineGroup), таких как Storyboard и ParallelTimeline, есть длительность по умолчанию Automatic, что означает, что они автоматически заканчиваются, когда последний ребенок прекращает играть.

В следующем примере анимированы ширина, высота и цвет заливки Rectangle. Длительность настраивается на временной шкале анимации и контейнера, что приводит к эффектам анимации, включая управление предполагаемой скоростью анимации и переопределение длительности дочерних временных шкал с длительностью временной шкалы контейнера.

Пример

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel Margin="20">
  
    <Rectangle Width="100" Height="100" Name="myRectangle">
      <Rectangle.Fill>
        <SolidColorBrush x:Name="MyAnimatedBrush" Color="Black" />
      </Rectangle.Fill>
      <Rectangle.Triggers>
      
        <!-- Animates the rectangle fill to yellow and width to 300. -->
        <EventTrigger RoutedEvent="Rectangle.Loaded">
          <BeginStoryboard>

            <!-- By default, TimelineGroup objects like Storyboard and ParallelTimeline have 
            a Duration of "Automatic". A TimelineGroup's automatic duration encompasses its 
            last-ending child. In this example, there is only one child of the Storyboard, the
            ParallelTimeline, so when the ParallelTimeline ends, the Storyboard duration will
            automatically end. -->
            <Storyboard>

              <!-- This ParallelTimeline has overriden its default duration of "Automatic" with
              a finite duration of half a second. This will force this Timeline to end after half a
              second even though its child Timelines have a longer duration (2 and 4 seconds respectively). 
              This cuts off the animation prematurely and the rectangle's fill will not go all the way to 
              yellow nor will the rectangle width get all the way to 300. Again, the default duration of a
              ParallelTimeline is "Automatic" so if you remove the finite duration, the ParallelTimeline
              will wait for its child timelines to end before it ends. -->

              <!-- Note: To specify a finite time in XAML, use the syntax of "days:hours:seconds". As mentioned,
              this ParallelTimeline has a duration of half a second. -->
              <ParallelTimeline Duration="0:0:0.5">

                <!-- For Animation Timelines like DoubleAnimation, the duration is one factor that
                determines the rate at which an animation appears to progress. For example, the DoubleAnimation
                below that animates the rectangle height will complete in only one second while the animation
                that animates the width willwill complete in 2 seconds which is relatively fast compared to the DoubleAnimation
                which animates the rectangle width over 4 seconds. -->
                <DoubleAnimation
                  Storyboard.TargetName="myRectangle"
                  Storyboard.TargetProperty="Height"
                  To="300" Duration="0:0:1" />

                <DoubleAnimation
                  Storyboard.TargetName="myRectangle"
                  Storyboard.TargetProperty="Width"
                  To="300" Duration="0:0:4" />

                <ColorAnimation
                  Storyboard.TargetName="MyAnimatedBrush"
                  Storyboard.TargetProperty="Color"
                  To="Yellow" Duration="0:0:2" />

              </ParallelTimeline>
            </Storyboard>
          </BeginStoryboard>
        </EventTrigger>
        
      </Rectangle.Triggers>
    </Rectangle>
  </StackPanel>
</Page>

См. также