Reputation: 493
I have button with a coloranimation, and a click event. The coloranimation animates the background of the button from gray to orange in 1 seconds, then reverse it. In the click event I load a lot of things (it takes around 4-5 secs).
My problem is that, when I click on the button the animation begins, but immediately stops after a few millisecs(click event started), and after the click event finished, it finishes the animation as well. I want that first finish the animation, then executes click event.
I googled a lot, and found the animation completed event and it's working, but is it possible somehow to make a basic solution for this, that I can use for all of my buttons in my program?
Thanks for the replies in advance!
BR, Zoli
EDIT: ---------------------------------------------
Do something like this:
PreviewMouseDown()
{
AnimateTheButton();
//Wait for the animation to be finished
}
Upvotes: 0
Views: 2085
Reputation: 1689
Okay, if you want beautiful and reusable solution check out what I wrote for you. Just add this class into your solution.
public sealed class AnimatedButton : Button
{
private bool _isAnimationRunning;
public static readonly DependencyProperty AnimationProperty =
DependencyProperty.Register("Animation", typeof(Storyboard), typeof(AnimatedButton));
public Storyboard Animation
{
get { return (Storyboard) GetValue(AnimationProperty); }
set { SetValue(AnimationProperty, value); }
}
protected override void OnPreviewMouseDown(System.Windows.Input.MouseButtonEventArgs e)
{
_isAnimationRunning = true;
if (Animation != null)
{
var clonedAnimation = Animation.Clone(); // Else we cannot subscribe Completed event
clonedAnimation.Completed += OnAnimationComplete;
clonedAnimation.Begin(this);
}
base.OnPreviewMouseDown(e);
}
protected override void OnClick()
{
if (Animation != null && _isAnimationRunning)
{
return;
}
base.OnClick();
}
private void OnAnimationComplete(object sender, EventArgs eventArgs)
{
_isAnimationRunning = false;
OnClick();
}
}
Usage. Just insert it into application resources:
<Application.Resources>
<Style x:Key="{x:Type controls:AnimatedButton}" TargetType="{x:Type TestWpf:AnimatedButton}">
<Setter Property="Animation">
<Setter.Value>
<Storyboard Duration="0:0:2">
<DoubleAnimation From="0.2" To="1" Storyboard.TargetProperty="Opacity">
</DoubleAnimation>
</Storyboard>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
And then you can use it like the usual button:
<local:AnimatedButton Click="OnAnimatedButtonClicked">
Super cool button
</local:AnimatedButton>
Upvotes: 2