Lightor
Lightor

Reputation: 493

Repeat calling of a DoubleAnimation while it is running

I have a DoubleAnimation call that is triggered on a button press. One button press causes the control to fade in (1000 milliseconds), pressed again it causes it to fade out (500 milliseconds). Now I notice if a user spams this button it will not fade back in. I have no problem with it ever failing to fade out. If the user then clicks again, which toggles the trigger, then clicks once more with a brief (~1 second) pause between clicks the control will then fade in without issue.

private void fader(bool fadeOut)
{

   if ((!fadeOut && gripLbl.Visibility == Visibility.Hidden) ||
       (fadeOut && gripLbl.Visibility == Visibility.Visible))
             return;

   if (fadeOut)
   {
        // Fade in grip
        gripLbl.Opacity = 0;
        gripLbl.Visibility = Visibility.Visible;
        gripLblAnimation = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(1000));
   }
   else
   {
        // Fade out grip
        gripLblAnimation = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(500));
        gripLblAnimation.Completed += delegate
        { gripLbl.Visibility = Visibility.Hidden; };
   }

   Timeline.SetDesiredFrameRate(gripLblAnimation, 60);
   gripLbl.BeginAnimation(FrameworkElement.OpacityProperty, gripLblAnimation);
}

Any help would be greatly appreciated, the only thing I can seem to find that helps is turning down the fade out timer down below 100 milliseconds. But if possible I would like it to just stop the current animation if it is in progress and start the new one.

I have tried nulling it out, starting a new BeginAnimation with the second parameter being null and using .Freeze() before hand in an attempt to cancel the current animation with no luck.

Upvotes: 1

Views: 96

Answers (1)

Setherith
Setherith

Reputation: 329

You need to incorpate a flag for when it's fading. Something like:

bool fading = true;

So that at the start you can put:

if(Fading) return;

That way if the user is mashing the button it will keep returning (i.e. ignoring them) until the fading boolean is reset at the end of the fade.

fading = false;

Upvotes: 1

Related Questions