I have an endless animation that hast to be reverted in certain circumstances. When it is reverted it has to run only once.
I initialize the animation in the constructor like this:
public RailComponent()
{
InitializeComponent();
RootCanvas.DataContext = this;
//RailAnimation
_railAnimation = new DoubleAnimation
{
RepeatBehavior = RepeatBehavior.Forever,
To = -_animationTo,
Duration = new Duration(TimeSpan.FromSeconds(TrackRunningTime))
};
...
}
And then add it to the Storyboard:
private void InitializeAnimations()
{
Storyboard.SetTarget(_railAnimation, RailImage);
Storyboard.SetTargetProperty(_railAnimation, new PropertyPath("(Image.RenderTransform).(TranslateTransform.X)"));
AddAnimation(_railAnimation);
...
}
Where AddAnimation is defined as:
protected void AddAnimation(DoubleAnimation animation)
{
saveAnimationHandling(() => Railstoryboard.Children.Add(animation));
}
private void saveAnimationHandling(Action animationAction)
{
TimeSpan current = GetCurrentStoryboardTime();
StopStoryboard();
animationAction();
StartStoryboard();
Railstoryboard.Seek(current);
SetVelocity();
}
I handle several Animations via the same Storyboard (i.e. add them or remove them). That's why I have to 'safely' handle them. The above code works just as intended (or hides its misbehaviour well.) But when I try to change some properties and add a Completed event, it never fires:
private void UpdateDirection(bool isBackward)
{
PauseRailStoryBoard();
var x = -RailImage.RenderTransform.Value.OffsetX;
var duration = x / _animationTo * TrackRunningTime;
_railAnimation.To = 0;
_railAnimation.Duration = TimeSpan.FromSeconds(duration);
_railAnimation.RepeatBehavior = new RepeatBehavior(1);
_railAnimation.Completed += _backwardRailAnimation_Completed;
ResumeRailStoryBoard();
}
void _backwardRailAnimation_Completed(object sender, EventArgs e)
{
_railAnimation.Completed -= _backwardRailAnimation_Completed;
}
Edit - alternate version that does also not work (saveHandleAnimation is ofc protected for this version):
private void UpdateDirection(bool isBackward)
{
saveHandleAnimation(() =>
{
var x = -RailImage.RenderTransform.Value.OffsetX;
var duration = x / _animationTo * TrackRunningTime;
_railAnimation.To = 0;
_railAnimation.Duration = TimeSpan.FromSeconds(duration);
_railAnimation.RepeatBehavior = new RepeatBehavior(1);
_railAnimation.Completed += _backwardRailAnimation_Completed;
});
}
I added a breakpoint into the event handling but it never seems to fire although the animation stops. Any pointers as to why would be very welcome. I did the very same thing with animations that are not endless and it seems to work just fine (I used a different Storyboard there).