Jack Ukleja
Jack Ukleja

Reputation: 13521

How to prevent an animation being interrupted [WPF]

For example I have an animation that triggers when mouse is clicked.

Problem is if you keep clicking the animation will restart.

I want to guarantee that an animation always plays through to completion.

Ideas?

Upvotes: 3

Views: 974

Answers (3)

mike
mike

Reputation: 1744

I ended up with something like below - triggering the animation from code and setting a flag that prevents triggering an animation again, if a previous animation has not been finished. I'm not sure, in how far this could be done XAML-only...

public class BorderAnimation
{
    private Border _border { get; }
    private DoubleAnimation _animation;
    private bool _isAnimating;

    public BorderAnimation(Border border)
    {
        _border = border;

        _animation = new DoubleAnimation
        {
            From = 0.0,
            To = 1.0,
            Duration = new Duration(TimeSpan.FromSeconds(.3)),
            AutoReverse = true,
        };

        _animation.Completed += _animation_Completed;
    }

    private void _animation_Completed(object sender, EventArgs e)
    {
        _isAnimating = false;
    }

    public void Animate()
    {
        Application.Current.Dispatcher.InvokeAsync(() => animateImpl(type)); //invoke required, because call will be from another thread in this particular case
    }

    private void animateImpl()
    {
        if (_isAnimating) return;
        _isAnimating = true;
        
        _border.BeginAnimation(Border.OpacityProperty, _animation);
    }
}

Upvotes: 0

Dabblernl
Dabblernl

Reputation: 16141

Still not the exact answer you are looking for, but this solved a problem I had involving a MouseDown trigger that started a new animation on top of a still running one:

<BeginStoryboard>
  <Storyboard AutoReverse="True">
    <ColorAnimation Storyboard.TargetProperty="(Label.Foreground).(SolidColorBrush.Color)"
                    To="Red" Duration="0:0:1"/>
  </Storyboard>

The problem with this animation is, that when it is triggered again before it completes, the autoreverse feature reverses it to the shade of red it had reached before it was triggered the second time, not to the original color it had before the first animation started.

In my case this was easily solved thus:

<BeginStoryBoard HandOffBehavior="Compose">

Upvotes: 1

Matt Hamilton
Matt Hamilton

Reputation: 204289

One trick I've found is to not include the "From" on my animations. That way the values will always start at whatever value the property you're animating has right now. That means that if the animation restarts, it won't reset the property back to its starting value and will instead look like it's continuing the orginal animation.

Upvotes: 2

Related Questions