How to stop an animation in C# / WPF?
I have something like this:
barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation( barProgress.Value, dNextProgressValue, new Duration(TimeSpan.FromSeconds(dDuration)));
Now, how would you stop that animation (the DoubleAnimation
)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...
Solution 1:
To stop it, call BeginAnimation
again with the second argument set to null
.
Solution 2:
When using storyboards to control an animation, make sure you set the second parameter to true in order to set the animation as controllable:
public void Begin(
FrameworkContentElement containingObject,
**bool isControllable**
)
Solution 3:
There are two ways to stop a BeginAnimation. The first is to call BeginAnimation again with the second parameter set to null. This will remove all animations on the property and revert the value back to its base value.
Depending on how you are using that value this may not be the behavior you want. The second way is to set the animations BeginTime to null then call BeginAnimation with it. This will remove that specific animation and leave the value at its current position.
DoubleAnimation myAnimation = new Animation();
// Initialize animation
...
// To start
element.BeginAnimation(Property, myAnimation);
// To stop and keep the current value of the animated property
myAnimation.BeginTime = null;
element.BeginAnimation(Property, myAnimation);