0

我的代码是这样的。我想动态创建网格。创造就是成功,但我无法为它的颜色设置动画。我的错误是什么?

        Grid[] grid = new Grid[99];
        for (int i = 0; i < 10; i++) {
            grid[i] = new Grid();
            grid[i].Width = grid[i].Height = 100;
            grid[i].Background = Brushes.WhiteSmoke;

            Storyboard sb = new Storyboard();
            ColorAnimation ca = new ColorAnimation(Colors.DarkTurquoise, TimeSpan.FromMilliseconds(250));
            Storyboard.SetTarget(ca, grid[i]);
            Storyboard.SetTargetProperty(ca, new PropertyPath("Fill.Color"));
            sb.Children.Add(ca);
            grid[i].MouseEnter += delegate(object sender2, MouseEventArgs e2) {
                sb.Begin(this);
            };

            stackMain.Children.Add(grid[i]);
        }
4

2 回答 2

4

WPFGrid没有Fill您必须使用的属性Background

 Storyboard.SetTargetProperty(ca, new PropertyPath("Background.Color"));
于 2013-01-16T04:55:51.163 回答
1

除了 sa_ddam 所说的之外,您还必须创建一个画笔,因为无法为内置画笔(如Brushes.WhiteSmoke您的示例中的示例)设置动画。

grid[i].Background = new SolidColorBrush(Colors.WhiteSmoke);
...

Storyboard.SetTargetProperty(ca, new PropertyPath("Background.Color"));

如果您省略情节提要并直接运行动画,它也可能会节省一些代码:

var brush = new SolidColorBrush(Colors.WhiteSmoke);
grid[i].Background = brush;

var ca = new ColorAnimation(Colors.DarkTurquoise, TimeSpan.FromMilliseconds(250));

grid[i].MouseEnter +=
    (o, e) => brush.BeginAnimation(SolidColorBrush.ColorProperty, ca);
于 2013-01-16T09:25:21.317 回答