2012-08-14 117 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