I'd like to repeat my animation for several times, every time the property of a target would change with it triggered or animation completed.
But the animition works only for the first time.
To simplify this, I just let a rectangle move from 0 to 400 in a canvas for 10 times. The code is followed.
I have searched questions like 'wpf repeat animation', which suggested to use seek()
method or rect.BeginAnimation(property, null)
, but doesn't work for me.
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;
}