How can i use DoubleAnimation in a loop in WPF?

221 Views Asked by At

I want to use animation in a for loop. But I can only see the last animation.

According to my search I have to use storyboard. My code is below.

Random rnd = new Random();
Storyboard sb = new Storyboard();

public MainWindow()
{
    InitializeComponent();

    for (int i = 1; i < 4; i++)
    {
        int temp = rnd.Next(1-3);
        move(cisim, 10*temp, 20*temp, 3);
    }
}

public void move( Image target,double oldX,double newX,int time)
{
    DoubleAnimation anim2 = new  DoubleAnimation(oldX,newX,TimeSpan.FromSeconds(time));

    Storyboard.SetTarget(anim2, target);
    Storyboard.SetTargetProperty(anim2, new PropertyPath("(Canvas.Left)"));

    sb.Children.Add(anim2);
    Canvas.BeginStoryboard(sb);
}

I want to see animation 3 times. For example:

Animation1->start - finish (after) Animation2->start - finish.    

When I run my code, I just see the last animation. What is the point I missed?

1

There are 1 best solutions below

1
Andy On BEST ANSWER

You need to set begintime in the second onwards to give previous ones time to do their thing.

https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.animation.timeline.begintime?view=netframework-4.8#System_Windows_Media_Animation_Timeline_BeginTime

At the moment all of your animations begin immediately.