How can I create a delay during a DoubleAnimation when using AutoReverse?

854 Views Asked by At

I have an animation which moves a grid to a specific place and then automatically goes back using AutoReverse. But since it's instant the user cannot read the message inside of it. How can I put a -for example- 5 seconds delay in the animation

Here is the method I have so far

public void ErrorMessage(Grid grid, ImageSource imageSource, String error_message)
    {
        Image_Broken_Component.Source = imageSource;
        TextBlock_Error_Message.Text = error_message;

        ThicknessAnimation ta = new ThicknessAnimation
        {
            From = grid.Margin,
            To = new Thickness(0, 50, 0, 0),
            Duration = new Duration(TimeSpan.FromSeconds(1)),
            AutoReverse = true
        };
        grid.BeginAnimation(Grid.MarginProperty, ta);
    }

The animation should play like this (using the From and To-values): 1 -> 0 -> wait 5s -> 1

1

There are 1 best solutions below

0
On

Instead of using the AutoReverse property, use a Storyboard:

https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/storyboards-overview

The BeginTime property can be used to delay the second animation to do basic sequencing as seen here:

XAML C# WPF Best efficient way to do an ordered sequence of animations

Then you can just sequence two ThicknessAnimations (one forward, one reverse) and set the BeginTime of the second one so that there is a pause before the animation is reversed.

Example code:

public void ErrorMessage(Grid grid, ImageSource imageSource, String error_message)
{
    Image_Broken_Component.Source = imageSource;
    TextBlock_Error_Message.Text = error_message;

    var storyboard = new Storyboard();

    storyboard.Children.Add(new ThicknessAnimation
    {
        From = grid.Margin,
        To = new Thickness(0, 50, 0, 0),
        Duration = new Duration(TimeSpan.FromSeconds(1))
    });

    storyboard.Children.Add(new ThicknessAnimation
    {
        From = new Thickness(0, 50, 0, 0),
        To = grid.Margin,
        Duration = new Duration(TimeSpan.FromSeconds(1)),
        BeginTime = TimeSpan.FromSeconds(6)
    });

    grid.BeginStoryboard(Grid.MarginProperty, storyboard);
}