简体   繁体   English

WPF:以编程方式对网格中的矩形颜色进行动画处理

[英]WPF: Programatically Animate Rectangle Color in Grid

How can I programatically change the Color of a Rectangle in my Grid? 如何以编程方式更改网格中矩形的颜色?

        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?

OK, I found a way to do this: 好的,我找到了一种方法:

I create a StoryBoard for each Grid item: 我为每个Grid项目创建一个StoryBoard:

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

and populate: 并填充:

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

Then I can animate like so: 然后,我可以像这样制作动画:

_animatableGridRectToGray[index].Begin(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM