さて、あなたが美しくて再利用可能な解決策が欲しいなら、私があなたのために書いたものをチェックしてください。このクラスをソリューションに追加するだけです。
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>