1

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;
}
HDQ
  • 45
  • 5

3 Answers3

3

you should register completed event first before calling begin statement like this:

storyboard.Completed += Storyboard_Completed;
 storyboard.Begin(this);
tabby
  • 1,878
  • 1
  • 21
  • 39
2

I think you misunderstand StoryBoard.Completed. You should apply the delegate on da.Completed.

        private void TargetAnimation(int i)
        {
            DoubleAnimation da = new DoubleAnimation();
            da.From = 0;
            da.To = 400;
            da.Duration = TimeSpan.FromSeconds(5);
            da.Completed += Storyboard_Completed;
            Storyboard.SetTargetName(da, "rect");
            Storyboard.SetTargetProperty(da, new PropertyPath(Canvas.LeftProperty));
            Storyboard storyboard = new Storyboard();
            storyboard.Children.Add(da);
            storyboard.Begin(this);
            //storyboard.Completed += Storyboard_Completed;
        }
mosyu
  • 57
  • 1
  • 8
0

You passed i as a parameter but you did not use it or its value to determine. So you have to limit TargetAnimation(int i) value using if statement that is equal to the target animation value which is i

Kindle Q
  • 944
  • 2
  • 19
  • 28