我有一个无尽的动画,在某些情况下必须恢复。当它被还原时,它只需要运行一次。
我像这样在构造函数中初始化动画:
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();
}
我通过同一个故事板处理多个动画(即添加或删除它们)。这就是为什么我必须“安全地”处理它们。上面的代码按预期工作(或很好地隐藏了它的不当行为。)但是当我尝试更改一些属性并添加一个 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 受此版本的 ofc 保护):
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;
});
}
我在事件处理中添加了一个断点,但尽管动画停止,它似乎从未触发。任何关于为什么的指示都会非常受欢迎。我对不是无穷无尽的动画做了同样的事情,它似乎工作得很好(我在那里使用了不同的故事板)。