2012-08-14 57 views
0

我有一个按钮与一个coloranimation,并单击事件。 coloranimation在1秒内将按钮的背景从灰色变为橙色,然后将其逆转。在点击事件中,我加载了很多东西(大约需要4-5秒)。WPF完成按钮动画之前执行点击

我的问题是,当我点击按钮时,动画开始,但几毫秒后立即停止(点击事件开始),点击事件结束后,它也完成了动画。 我想先完成动画,然后执行点击事件。

我搜索了很多,并发现动画完成的事件,它的工作,但它有可能以某种方式为此做出基本的解决方案,我可以使用我的程序中的所有按钮?

感谢您提前回复!

BR, 佐利

编辑:------------------------------------ ---------

做这样的事情:

PreviewMouseDown() 
{ 
    AnimateTheButton(); 
    //Wait for the animation to be finished 
} 
+0

参见[VisualStateManager(http://msdn.microsoft.com/en-us/ library/system.windows.visualstatemanager.aspx)类和它的[用于按钮](http://msdn.microsoft.com/en-us/library/ms753328.aspx) – dvvrd 2012-08-14 08:59:30

+0

我发现什么都没有用。 – 2012-08-14 11:24:16

+0

哦,对不起,我误解了这个问题。那么也许你可以在PreviewMouseUp事件触发时禁用动画? – dvvrd 2012-08-14 11:40:57

回答

2

好吧,如果你要的是美丽,可重复使用的解决方案检查出什么,我为你写。 只需将此类添加到您的解决方案中即可。

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> 
+0

是的,这是答案,我正在等待:)。 我想创建一个自己的按钮类,但我希望也许有一个更简单的解决方案。 感谢您的回答! :) – 2012-08-15 06:44:40