2017-05-28 228 views
0

我想實現一個動畫,我將控件從一行移動到另一個使用for循環。在for循環中動畫wpf控件

private void AnimateStoryBoard(int number) 
    { 
     Storyboard _currentStoryBoard = new Storyboard(); 

     //Row Animation 
     Int32Animation newrowanimation = new Int32Animation(); 
     newrowanimation.From = number; 
     newrowanimation.To = number+1; 
     newrowanimation.Duration = new TimeSpan(0, 0, 0, 0, 500); 

     Storyboard.SetTargetProperty(newrowanimation, new PropertyPath("(Grid.Row)")); 

     _currentStoryBoard.Children.Add(newrowanimation); 

     Storyboard.SetTarget(newrowanimation, myrectangle); 

     _currentStoryBoard.Begin(); 
    } 

,我使用

 for (int i = 0; i < 10; i++) 
     { 
      AnimateStoryBoard(i); 
     } 

現在調用它,當我運行此我希望動畫去從1到2則2〜3,然後3到4 ... 9-10。然而,動畫直接跳到9,然後是10.

另外我怎樣才能做到這一點在XAML?,請注意,這裏的數字10只是一個例子。數字必須來自代碼隱藏,它會不斷變化。

+1

喲,不要等到之前的動畫才能開始下一個動畫。這留下了最後的動畫。您應該等待動畫在循環內完成 –

+0

這似乎與您之前詢問的問題完全相同:https://stackoverflow.com/questions/44212995/repeating-storyboard-animation-using-for-loop 。不要刪除和重新發布問題。 **解決您最初發布的問題。** –

回答

2

恕我直言,沒有必要重新發明輪子:key frame animation也意味着用於這一目的。

因此,創建你需要的動畫,可以使用類似:

Storyboard storyBoard = new Storyboard(); 
int gridRowLimit = 5; // here you can set how many rows your grid has 

Int32AnimationUsingKeyFrames intKeyFrame = new Int32AnimationUsingKeyFrames(); 
intKeyFrame.Duration = new TimeSpan(0, 0, 0, 0, gridRowLimit * 500); 

for (int i = 1; i < gridRowLimit; i++) 
{ 
    intKeyFrame.KeyFrames.Add(new DiscreteInt32KeyFrame(i)); 
} 

Storyboard.SetTargetProperty(intKeyFrame, new PropertyPath("(Grid.Row)")); 
Storyboard.SetTarget(intKeyFrame, yourControl); 

storyBoard.Children.Add(intKeyFrame); 
storyBoard.Begin(); 

我希望它能幫助。

+0

正是我想要的。謝謝 – Rohit

2

正如Alexander Clare在評論中提到的那樣,您必須在故事板中設置幾個動畫。使用循環的解決方案不起作用,因爲在運行循環時您的方法不會返回,因此UI線程將無法呈現故事板/動畫引起的更改。

一個解決方案將是一個單個的Storyboard實例,其中包含可變數量的動畫(每行一個動畫)。使用BeginTime屬性來錯開動畫。我建議你在這些動畫之間使用從40ms到100ms的值(我不會低於20ms)。

在代碼中,這將是這個樣子:

private void AnimateStoryboard(int number) 
{ 
    // Create the storyboard that will be played 
    var storyboard = new Storyboard(); 

    // Create the animation objects for each row change and add them to the storyboard 
    var currentBeginTime = TimeSpan.Zero; 
    for (var i = 0; i < number; i++) 
    { 
     var animation = new Int32Animation(); 
     // Set all the properties that you set on your animation objects before, and additionally use BeginTime 
     animation.BeginTime = currentBeginTime; 
     storyboard.Children.Add(animation); 

     // Update the currentBeginTime to achieve the staggering effect 
     currentBeginTime += TimeSpan.FromMilliseconds(50); 
    } 

    // Finally, start the Storyboard to run all animations 
    storyboard.Begin(); 

}