好的,如果您想要漂亮且可重复使用的解决方案,请查看我为您写的内容。只需将此类添加到您的解决方案中即可。
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();
}
}
用法。只需将其插入应用程序资源:
<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>
然后你可以像通常的按钮一样使用它:
<local:AnimatedButton Click="OnAnimatedButtonClicked">
Super cool button
</local:AnimatedButton>