2011-10-24 78 views
1

如何以編程方式更改網格中矩形的顏色?WPF:以編程方式在網格中動畫矩形顏色

 ColorAnimation myColorAnimation = new ColorAnimation(); 
     myColorAnimation.From = Colors.Red; 
     myColorAnimation.To = Colors.Blue; 
     myColorAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500)); 
     myColorAnimation.AutoReverse = false; 

     myStoryboard = new Storyboard(); 
     myStoryboard.Children.Add(myColorAnimation); 
     Storyboard.SetTargetName(myColorAnimation, ?); // What do I put here 
     Storyboard.SetTargetProperty(myColorAnimation, new PropertyPath //What do I put here? 
+0

你能爲你的矩形和它放置的網格顯示xaml代碼嗎? –

回答

0

OK,我發現了一個辦法做到這一點:我爲每個網格項目故事板

List<Storyboard> _animatableGridRectToGray = new List<Storyboard>(); 
    List<Storyboard> _animatableGridRectToWhite = new List<Storyboard>(); 

並填充:

private void initAnimatableGridRectangles() 
{ 
    int index = 1; 
    foreach (Rectangle rect in SequenceGrid.Children) 
    { 
     SolidColorBrush tempBrush = new SolidColorBrush(); 
     rect.Fill = tempBrush; 
     string brushName = "Brush" + index; 
     _gridBrushes.Add(brushName, tempBrush); 
     this.RegisterName(brushName, tempBrush); 

     Storyboard tempSBToGray = new Storyboard(); 
     Storyboard tempSBToWhite = new Storyboard(); 
     ColorAnimation tempColAnimToGray = getAnimToGray(); 
     ColorAnimation tempColAnimToWhite = getAnimToWhite(); 
     tempSBToGray.Children.Add(tempColAnimToGray); 
     tempSBToWhite.Children.Add(tempColAnimToWhite); 
     Storyboard.SetTargetName(tempColAnimToGray, brushName); 
     Storyboard.SetTargetName(tempColAnimToWhite, brushName); 
     Storyboard.SetTargetProperty(tempColAnimToGray, new PropertyPath(SolidColorBrush.ColorProperty)); 
     Storyboard.SetTargetProperty(tempColAnimToWhite, new PropertyPath(SolidColorBrush.ColorProperty)); 
     _animatableGridRectToGray.Add(tempSBToGray); 
     _animatableGridRectToWhite.Add(tempSBToWhite); 
     index++; 
    } 
} 


private ColorAnimation getAnimToGray() 
{ 
    ColorAnimation colAnim = new ColorAnimation(); 
    colAnim.To = Colors.Gray; 
    colAnim.Duration = new Duration(TimeSpan.FromMilliseconds(500)); 
    colAnim.AutoReverse = false; 
    return colAnim; 
} 

private ColorAnimation getAnimToWhite() 
{ 
    ColorAnimation colAnim = new ColorAnimation(); 
    colAnim.To = Colors.White; 
    colAnim.Duration = new Duration(TimeSpan.FromMilliseconds(500)); 
    colAnim.AutoReverse = false; 
    return colAnim; 
} 

然後我就可以動畫像這樣:

_animatableGridRectToGray[index].Begin(this);