我想重复我的动画几次,每次目标的属性都会随着触发或动画完成而改变。
但动画仅在第一次有效。
为了简化这一点,我只是让一个矩形在 Canvas 中从 0 移动到 400 10 次。代码如下。
我搜索了诸如“wpf重复动画”之类的问题,建议使用seek()
方法或rect.BeginAnimation(property, null)
,但对我不起作用。
private void init()
{
Rectangle rect = new Rectangle();
this.RegisterName("rect", rect);
rect.Height = 100;
rect.Width = 50;
rect.Fill = Brushes.LightBlue;
Canvas.SetTop(rect, 0);
Canvas.SetLeft(rect, 0);
myCanvas.Children.Add(rect);
TargetAnimation(0);
}
private void TargetAnimation(int i)
{
DoubleAnimation da = new DoubleAnimation();
da.From = 0;
da.To = 400;
da.Duration = TimeSpan.FromSeconds(5);
Storyboard.SetTargetName(da, "rect");
Storyboard.SetTargetProperty(da, new PropertyPath(Canvas.LeftProperty));
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(da);
storyboard.Completed += Storyboard_Completed;
storyboard.Begin(this);
}
private void Storyboard_Completed(object sender, EventArgs e)
{
if (i < 10)
TargetAnimation(++i);
else
return;
}
最佳答案
在调用 begin 语句之前,您应该先注册完成的事件 像这样:
storyboard.Completed += Storyboard_Completed;
storyboard.Begin(this);
关于c# - 我的 wpf 动画代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37386422/