I try to animate a DependencyProperty from a value to a target value (in code) and when the animation finishes (or is canceled) set the final value to the property. The final value would be either the To value if the animation finishes or the current computed value (by the animation) when the animation is canceled.
By default the Animation doesn't have this behavior and an Animation doesn't change the actual value even if it has completed.
A failed attempt
A while ago I wrote this helper method to achieve the mentioned behavior:
static void AnimateWithAutoRemoveAnimationAndSetFinalValue(IAnimatable element,
DependencyProperty property,
AnimationTimeline animation)
{
var obj = element as DependencyObject;
if (obj == null)
throw new ArgumentException("element must be of type DependencyObject");
EventHandler handler = null;
handler = (sender, e) =>
{
var finalValue = obj.GetValue(property);
//remove the animation
element.BeginAnimation(property, null);
//reset the final value
obj.SetValue(property, finalValue);
animation.Completed -= handler;
};
animation.Completed += handler;
element.BeginAnimation(property, animation);
}
Unfortunately the Completed event doesn't seem to fire if the Animation is removed by someone calling BeginAnimation(property,null) and therefore I cannot set the final value correctly when an Animation is canceled. What is worse I cannot remove the event handler either...
Does someone know how to do this in a clean way?