2010-12-08 102 views
1

我在一個數組中存儲一組控件,我試圖在一個循環中逐個動畫所有控件,但是我只能看到最後一個動畫?WP7多控制動畫問題

for (int i = 0; i < 4; i++) 
      { 
       Dispatcher.BeginInvoke(() => 
       { 
        var sb = new Storyboard(); 
        sb = CreateStoryboard(1.0, 0.0, this.Lights[0, i]); 
        sb.Begin(); 
       }); 
       } 


private Storyboard CreateStoryboard(double from, double to, DependencyObject targetControl) 
     { 
      Storyboard result = new Storyboard(); 

      DoubleAnimation animation = new DoubleAnimation(); 
      animation.From = from; 
      animation.To = to; 
      animation.Duration = TimeSpan.FromSeconds(1); 
      animation.BeginTime = TimeSpan.FromSeconds(1); 
      animation.AutoReverse = false; 
      Storyboard.SetTarget(animation, targetControl); 
      Storyboard.SetTargetProperty(animation, new PropertyPath(UIElement.OpacityProperty)); 

      result.Children.Add(animation); 
      return result; 
     } 
+0

這是否方法上的改變意味着你的最後一個問題(http://stackoverflow.com/questions/4384159/wp7-ui-updating-issue)是不再有效? – 2010-12-08 10:37:21

回答

1

我無法解釋這種行爲。如果沒有Dispatcher.BeginInvoke,您只會同時讓所有項目褪色。但是我不明白爲什麼在使用BeginInvoke時不會得到相同的結果。仍然不是你以後的樣子。您需要先後對動畫進行排序。

可能做到這一點的最好辦法是使用一個單一的故事板與多個動畫,在測序動畫畢竟是一個故事板整點。

private DoubleAnimation CreateAnimation(double from, double to, DependencyObject targetControl, int index) 
    { 
     DoubleAnimation animation = new DoubleAnimation(); 
     animation.From = from; 
     animation.To = to; 
     animation.Duration = TimeSpan.FromSeconds(1); 
     animation.BeginTime = TimeSpan.FromSeconds(1 * index); 
     animation.AutoReverse = false; 
     Storyboard.SetTarget(animation, targetControl); 
     Storyboard.SetTargetProperty(animation, new PropertyPath(UIElement.OpacityProperty)); 

     return animation; 
    } 

請注意額外的index參數,該參數用於指定何時開始動畫。

現在你的代碼很簡單: -

var sb = new Storyboard();  

for (int i = 0; i < 4; i++)  
{  
    sb.Children.Add(CreateAnimation(1.0, 0.0, this.Lights[0, i], i);  
} 

sb.Begin();