Search code examples
wpfwpf-animation

How to start animation, wait for 'X' seconds and then undo animation?


I have an animation that brings a text block down when I have an error that I want to display to the user. Currently, it comes down in .5 seconds. Is there a way to bring it down in .5 seconds, keep it there for 10 seconds, and then hide it in .5 seconds? I found the auto reverse property, which takes care of the beginning and ending, but I have not found a way to keep the text block displayed for a specified period of time. Any help would be appreciated!

<Window.Resources>
    <Storyboard x:Key="MessageSlide" AutoReverse="True">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="textBlock">
            <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="50"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>
</Window.Resources>
<Window.Triggers>
    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
        <BeginStoryboard Storyboard="{StaticResource MessageSlide}"/>
    </EventTrigger>
</Window.Triggers>

Solution

  • Add another KeyFrame that just holds the value:

    <DoubleAnimationUsingKeyFrames ... AutoReverse="True">
        <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="50"/>
        <DiscreteDoubleKeyFrame KeyTime="0:0:5.5" Value="50"/>
    </DoubleAnimationUsingKeyFrames>
    

    You may as well just set the animation's Duration:

    <DoubleAnimationUsingKeyFrames ... Duration="0:0:5.5" AutoReverse="True">
        <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="50"/>
    </DoubleAnimationUsingKeyFrames>