WPF:以编程方式为网格中的矩形颜色设置动画

时间:2011-10-24 01:28:41

标签: c# wpf animation

如何以编程方式更改网格中矩形的颜色?

        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?

1 个答案:

答案 0 :(得分:0)

好的,我找到了一种方法:

我为每个Grid项创建一个StoryBoard:

    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);