Search code examples
c#wpfanimation

Pause between repeats in an animation in WPF


I have applied the following FadeIn/FadeOut animation to a Canvas in WPF.

var fadingInOutAnimation = new DoubleAnimation
{
    From = 1,
    To = 0,
    Duration = new Duration(TimeSpan.FromMilliseconds(1000)),
    AutoReverse = true,
    RepeatBehavior = RepeatBehavior.Forever,
};

MyCanvas.BeginAnimation(OpacityProperty, fadingInOutAnimation);

Now I want it to pause for 1 second when it reaches the end of the animation before repeating again.

So it is like this:

Animation --- Pause (1 Sec) --- Animation --- Pause (1 Sec) and so on.

Solution

  • You might add a Storyboard that does the auto-reversing and repetition, but that has a longer duration than the animation:

    var fadeInOutAnimation = new DoubleAnimation()
    {
        From = 1,
        To = 0,
        Duration = TimeSpan.FromSeconds(1),
    };
    
    var storyboard = new Storyboard
    {
        Duration = TimeSpan.FromSeconds(2),
        AutoReverse = true,
        RepeatBehavior = RepeatBehavior.Forever
    };
    
    Storyboard.SetTarget(fadeInOutAnimation, MyCanvas);
    Storyboard.SetTargetProperty(fadeInOutAnimation,
                                 new PropertyPath(Canvas.OpacityProperty));
    
    storyboard.Children.Add(fadeInOutAnimation);
    MyCanvas.BeginStoryboard(storyboard);