我有一个无穷无尽的动画,在某些情况下会被还原。当它被还原时,它只能运行一次。
我在构造函数中初始化动画,如下所示:
public RailComponent()
{
InitializeComponent();
RootCanvas.DataContext = this;
//RailAnimation
_railAnimation = new DoubleAnimation
{
RepeatBehavior = RepeatBehavior.Forever,
To = -_animationTo,
Duration = new Duration(TimeSpan.FromSeconds(TrackRunningTime))
};
...
}
然后将其添加到故事板:
private void InitializeAnimations()
{
Storyboard.SetTarget(_railAnimation, RailImage);
Storyboard.SetTargetProperty(_railAnimation, new PropertyPath("(Image.RenderTransform).(TranslateTransform.X)"));
AddAnimation(_railAnimation);
...
}
其中AddAnimation定义为:
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();
}
我通过同一个Storyboard处理几个动画(即添加或删除它们)。这就是我必须'安全'处理它们的原因。上面的代码就像预期的那样工作(或者很好地隐藏它的错误行为。)但是当我尝试更改某些属性并添加一个Completed事件时,它永远不会触发:
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;
}
编辑 - 也不起作用的备用版本(saveHandleAnimation受此版本保护):
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;
});
}
我在事件处理中添加了一个断点,但是虽然动画停止了但它似乎永远不会触发。关于为什么会受到欢迎的任何指示。我做了同样的事情,动画不是无穷无尽的,似乎工作得很好(我在那里使用了不同的故事板)。