2010-02-24 124 views
1

如何從WPF元素中刪除正在運行的動畫,以使其Completed事件不會觸發?WPF:防止「已完成」事件在刪除動畫後觸發

提供的解決方案爲herehere刪除動畫的可見效果,但Completed事件在動畫完成時仍會觸發。

下面是一些代碼,演示了我的問題(這是在一個標籤,一個按鈕的窗口背後的代碼,和一個TextBox):

int _count = 0; 

    private void button1_Click(object sender, RoutedEventArgs e) { 
     myLabel.Content = "Starting animation: " + _count++; 

     // Cancel any already-running animations and return 
     // the label opacity to 1.0. 
     myLabel.BeginAnimation(Label.OpacityProperty, null); 
     myLabel.Opacity = 1.0; 

     // Create a new animation to fade out the label. 
     DoubleAnimation opacityAnim = new DoubleAnimation(1.0, 0.0, TimeSpan.FromSeconds(2), FillBehavior.Stop) { 
      BeginTime = TimeSpan.FromSeconds(3) 
     }; 
     opacityAnim.Completed += (sndr, ev) => { 
      myTextbox.Text += Environment.NewLine + "Completed fired."; 
     }; 

     // Start the countdown/animation. 
     myLabel.BeginAnimation(Label.OpacityProperty, opacityAnim); 
    } 

如何刪除的動畫,使得它不會提高其Completed事件?

回答

3

從已完成的情況下取消...這也意味着你必須從lambda來顯式方法重寫完成事件處理程序:

DoubleAnimation _opacityAnim; // Created somewhere else. 

    private void button1_Click(object sender, RoutedEventArgs e) 
    { 
    myLabel.Content = "Starting animation: " + _count++; 

    // Cancel any already-running animations and return 
    // the label opacity to 1.0. 
    _opacityAnim.Completed -= AnimationCompleted; 

    myLabel.BeginAnimation(Label.OpacityProperty, null); 
    myLabel.Opacity = 1.0; 

    // Create a new animation to fade out the label. 
    opacityAnim.Completed += AnimationCompleted; 

    // Start the countdown/animation. 
    myLabel.BeginAnimation(Label.OpacityProperty, opacityAnim); 
} 

private void AnimationCompleted(object sender, EventArgs e) 
{ 
     myTextbox.Text += Environment.NewLine + "Completed fired."; 
} 
+0

迷人......我還以爲這之前,但估計會依然火該事件是因爲您馬上添加了一個處理程序,並且它是相同的動畫對象。然而,在實際測試它(新穎的概念)後,我發現它可以按照需要運行! (可能你能指出我對這是爲什麼的解釋嗎?)在代碼中讀取有點不直觀,但我很高興它可以工作。謝謝! – 2010-02-24 19:19:29

相關問題