2011-03-15 149 views
2

這看起來應該是一件容易的事,但我無法讓WPF故事板暫停。我打電話暫停,沒有任何反應 - 它保持正確的動畫。如何暫停故事板?

這裏有一個攝製情況:該動畫的寬度按鈕。如果您單擊該按鈕,則會在故事板上調用暫停。我希望,只要我點擊按鈕,其寬度應該停止改變;相反,它的寬度保持正確的動畫,就像我從來沒有叫過暫停。

NameScope.SetNameScope(this, new NameScope()); 
var storyboard = new Storyboard(); 

var button = new Button { Content = "Pause", Name = "pause" }; 
this.Content = button; 
RegisterName(button.Name, button); 
var animation = new DoubleAnimation(0, 200, TimeSpan.FromSeconds(5)); 
Storyboard.SetTargetName(animation, button.Name); 
Storyboard.SetTargetProperty(animation, 
    new PropertyPath(FrameworkElement.WidthProperty)); 
storyboard.Children.Add(animation); 

button.Click += (sender, e) => { storyboard.Pause(this); }; 
storyboard.Begin(this); 

從我瞭解的文檔,我應該叫Pause(FrameworkElement)超載與我傳遞給Begin相同的參數,因此Pause(this)以上。但我也試過storyboard.Pause(),行爲沒有變化。我也嘗試storyboard.Pause(button)只是爲了它,再次沒有效果。我會盡量storyboard.Pause(storyboard)storyboard.Pause(animation)只是用盡的可能性,但沒有一個編譯 - 它想要一個FrameworkElement的(或FrameworkContentElement上)。

如何獲得storyboad暫停?

回答

4

我不知道爲什麼你正在使用weired SetNameScope等清除你的代碼,我可以讓它工作:

 //NameScope.SetNameScope(this, new NameScope()); 
     var storyboard = new Storyboard(); 

     var button = new Button { Content = "Pause", Name = "pause" }; 
     this.Content = button; 
     //RegisterName(button.Name, button); 
     var animation = new DoubleAnimation(0, 200, TimeSpan.FromSeconds(5)); 
     Storyboard.SetTarget(animation, button); 
     Storyboard.SetTargetProperty(animation, 
      new PropertyPath(FrameworkElement.WidthProperty)); 
     storyboard.Children.Add(animation); 

     button.Click += (sender, e) => { storyboard.Pause(); }; 
     storyboard.Begin(); 
+0

呵呵。 MSDN文檔堅持認爲你必須設置一個名稱範圍,但是你的版本更簡單,並且(b)可以工作。我要買它。 – 2011-03-15 00:52:58

+0

我不得不說我有點困惑。我已經5年了編程WPF,這是我第一次見過名稱範圍&RegisterName ...的用法: -/ – 2011-03-15 00:55:29

+0

看起來像代碼更改的神奇組合是(a)使用SetTarget而不是SetTargetName,並且(b)使用無參數'Begin'和'Pause'而不是傳遞'this'。 NameScope是無害的,但在使用SetTarget時沒有必要。 – 2011-03-15 00:57:58