R – Programmatically reverse Storyboard

storyboardwpf

I have the following storyboard:

<Window.Resources>
    <Storyboard x:Key="ButtonsAnim">
        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="topRightButton" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)">
            <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
            <SplineDoubleKeyFrame KeyTime="00:00:00.2000000" Value="-100"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="topRightButton" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)">
            <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
            <SplineDoubleKeyFrame KeyTime="00:00:00.2000000" Value="100"/>
...

It basically moves some buttons around in a canvas.

This is the code that starts the animation:

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    Storyboard sb = (Storyboard)Resources["ButtonsAnim"];
    storyBoard = sb;
    storyBoard.Begin(this, true);

}

What I am trying to do is to reset the animation when I click a button which hides the window. When the window reappears the animation should start from the beginning.

I tried using storyBoard.Begin(this, true) when the application reappears but for this first milliseconds the buttons are at their last position.

I then tried storyBoard.seek(TimeSpan.Zero) before hiding the window but it fails:

System.Windows.Media.Animation
Warning: 6 : Unable to perform action
because the specified Storyboard was
never applied to this object for
interactive control.; Action='Seek';
Storyboard='System.Windows.Media.Animation.Storyboard';
Storyboard.HashCode='24901833';
Storyboard.Type='System.Windows.Media.Animation.Storyboard';
TargetElement='System.Windows.Media.Animation.Storyboard';
TargetElement.HashCode='24901833';
TargetElement.Type='System.Windows.Media.Animation.Storyboard'

I also tried storyBoard.remove(this) before hiding the window, same effect: the buttons are at their last position.

Any ideas?

Thank you.

Best Answer

To use StoryBoard.Remove() this way - you should keep reference to your storyboard object.

Like this:

Storyboard myStoryBoard; 

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    myStoryBoard = (Storyboard)Resources["myStoryBoard"];
    myStoryBoard.Begin();

}

void sbRemoveEvent()
{
    myStoryBoard.Remove();  
}
Related Topic