Cristian M
Cristian M

Reputation: 725

What is the best way to wait for an animation to finish in MVVM?

I have a MetroTile with a periodic animation (written in C# code) and a DataGrid. When the grid has validation errors, the tile command's CanExecute() in the viewmodel returns false and the tile is disabled.

This is the animation code executed in the timer's tick method:

DoubleAnimation db = new DoubleAnimation(startStopTile.ActualHeight, 0, TimeSpan.FromSeconds(0.5));
db.FillBehavior = FillBehavior.Stop;
startStopTile.BeginAnimation(HeightProperty, db);

The problem is that the tile can be disabled during the animation and freezes in the middle of it. What is the best way to wait for the animation to complete before the tile is disabled?

I thought I could update a viewmodel property (i.e., bool AnimationCompleted) when the animation finishes and wait in a while loop in the CanExecute() for it to turn true, but I'm not sure if it's the best approach.

Upvotes: 1

Views: 628

Answers (1)

d.moncada
d.moncada

Reputation: 17402

Why don't you just notify the ViewModel after the animation completes using the Animation complete event? There is no need to wait via while loop (this is bad because it will block the UI).

db.Completed += OnAnimationComplete;

private void OnAnimationComplete(object sender, EventArgs e)
{
    db.Completed -= OnAnimationComplete;

    // Notify ViewModel that it finished
    //
    // example: viewModel.NotifyAnimationComplete();
}

Upvotes: 1

Related Questions