Short solution for short problems

Start and stop animations in WPF from code behind

It sounds simple, and it is.

I followed the simple Microsoft demonstration which you can find here.

I had a start and stop button and defined a trigger on the button to start the animation when it was clicked. Still was working fine. Then I decided to use the same button to start and stop the animation and this is where I got stuck for a short while.

The trigger on the XAML defined that each time the click was called, the event should be triggered. But when I stopped the animation in the onclick, the animation was still running. So this means the trigger is executed after the onclick event is handled. To solve this I removed the trigger and placed the storyboard with the animations in the resources:


        <Storyboard x:Key="ButtonStoryBoard">

            <DoubleAnimation Name="btnStartdoubleAnimation"



                                        From="1.0" To="0.0" Duration="0:0:5"

                                        AutoReverse="True" RepeatBehavior="Forever" />

            <ColorAnimation Storyboard.TargetName="MyColorBrush" 





                                        AutoReverse="True" RepeatBehavior="Forever"/>

            <ColorAnimation Storyboard.TargetName="MyBorderColorBrush" 





                                        AutoReverse="True" RepeatBehavior="Forever"/>




Then I removed the trigger in XAML and simply started and stopped the storyboard animations in code.

It looks like this:

Storyboard storyboard;


        private void btnStart_Click(object sender, RoutedEventArgs e)


            storyboard = this.TryFindResource("ButtonStoryBoard") as Storyboard;


            if (!_started)



                if (storyboard != null)


                    storyboard.Begin(btnStart, true);




                _started = true;





                _started = false;


                if (storyboard != null)






                btnStart.Content = "Start";



So the animations are started and stopped from the code behind.

Found most of the info here.