Is this intended behavior? If I have a Label animating across the screen and I remove it with canvas1.Children.Remove(label)
it seems that the animation continues to run behind the scenes and even fires AnimationCompleted
even though I have no references to the label or to the DoubleAnimation
I used to animate it with. What if the animation was endless?
Do I really need to do my own bookkeeping and stop the animation myself when removing a control from its parent?
Do I really need to do my own bookkeeping
Yes, you can only Animate
Dependency
properties and Dependency
properties are static
so even if your Control
is no longer referenced the Animation
will continue.
Depending on the purpose of your Animation
you may it may be as simple as setting the Animations FillBehavior
to Stop
animation.FillBehavior = FillBehavior.Stop;
This will stop the animation TimeLine
when it completes, but this is not always a great solution if you have repeating animations or animations that set certain values as when the animation stops the property animated will return to its original value immediately.
If FillBehavior.Stop
does not work in your situation you call stop Animations
and Storyboards
in other ways.
If the Animation
is a Storyboard
you can call StopStoryboard
When you use BeginStoryboard
you can supply a Name
, which you can then use in StopStoryboard
:
<BeginStoryboard Name="myStoryboard" ......... />
<StopStoryboard BeginStoryboardName="myStoryboard" />
Trigger Storyboard example:
<Trigger>
<Trigger.EnterActions>
<BeginStoryboard Name="myStoryboard">
<Storyboard ..... />
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<StopStoryboard BeginStoryboardName="myStoryboard" />
</Trigger.ExitActions>
</Trigger>
Or in code behind you can just call Stop
on your storyboard:
myStoryboard.Stop();
If you are creating a simple Animation in code behind you can stop it by applying a null
TimeLine
to the DependencyProperty
you animated.
Example:
// Start
myLabel.BeginAnimation(Canvas.LeftProperty, new DoubleAnimation(10.0, 100.0, new Duration(TimeSpan.FromSeconds(5)));
// Stop
myLabel.BeginAnimation(Canvas.LeftProperty, null);