Search code examples
c#wpfanimationdoubleanimation

How to create a time delay between two animations in wpf


I am new in WPF, I just want to animate two objects one after the other. That means that 2nd animation should start after 1st is finished. I tried using Timer and Sleep methods which didn't work well. Below is a sample code:

DoubleAnimation da1 = new DoubleAnimation()
{

   From = 10,
   To = 200,
   Duration = new System.Windows.Duration(TimeSpan.FromSeconds(sec)),
};


temLabel1.BeginAnimation(Canvas.TopProperty, da1);
Delay(); // Delay when busy

DoubleAnimation da2 = new DoubleAnimation()
{

   From = 300,
   To = 500,
   Duration = new System.Windows.Duration(TimeSpan.FromSeconds(sec)),
};

ItemLabels2.BeginAnimation(Canvas.LeftProperty, da2);

I am using Timer to create a time delay between two animations

 /* Setting Timer For delay during animation */

  timer.Interval = sec * 1000 + 50;
  timer.Elapsed += Timer_Elapsed;    

The code for delay function is :

void Delay()
{
     busy = true;
     timer.Start();

     while (busy) {}
}

Timer Elapsed Event Handler

private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    busy = false;
    timer.Stop();
 }

Please correct me where I am wrong. I don't want to use Note: DoubleAnimation.Completed event handler for this purpose because It will be difficult when dealing with and animating a collection of objects through loop. Your Response will be appreciated greatly.


Solution

  • Try this:

    private int sec = 2;
    
    private async Task StartAnimation()
    {
        await StartAnimationForLabel1();
        await StartAnimationForLabel2();
    }
    
    private async Task StartAnimationForLabel1()
    {
        DoubleAnimation da1 = new DoubleAnimation()
        {
            From = 10,
            To = 200,
            Duration = new System.Windows.Duration(TimeSpan.FromSeconds(sec)),
        };
         ItemLabel1.BeginAnimation(Canvas.TopProperty, da1);
        await Task.Delay(sec * 1000); 
    }
    
    private async Task StartAnimationForLabel2()
    {
        DoubleAnimation da2 = new DoubleAnimation()
        {
            From = 300,
            To = 500,
            Duration = new System.Windows.Duration(TimeSpan.FromSeconds(sec)),
    
        };
        ItemLabels2.BeginAnimation(Canvas.LeftProperty, da2);
        await Task.Delay(sec * 1000);
    }
    

    to know more about Asynchronous Programming with Async and Await see Here

    Require .NET Framework 4.5 or more