简体   繁体   中英

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 (ie, 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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM