WPF:如何制作颜色变化的动画?
我有一个网格,一个窗口根元素。我想应用一个动画,它会在 5 秒内将其背景颜色从白色更改为绿色。这就是我所做的:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ColorAnimation animation;
animation = new ColorAnimation();
animation.From = Colors.White;
animation.To = Colors.Green;
animation.Duration = new Duration(TimeSpan.FromSeconds(5));
rootElement.BeginAnimation(Grid.BackgroundProperty, animation);
}
代码不起作用。一切都没有改变。我哪里出错了?谢谢。
I have a grid, a window root element. I want to apply an animation which would change it's background color from white to green in 5 seconds. Here's what I did:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ColorAnimation animation;
animation = new ColorAnimation();
animation.From = Colors.White;
animation.To = Colors.Green;
animation.Duration = new Duration(TimeSpan.FromSeconds(5));
rootElement.BeginAnimation(Grid.BackgroundProperty, animation);
}
The code doesn't work. Nothing is changing. Where am I making a mistake? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决了!
这里有一个解释:
我最初的错误是我想通过为其分配颜色来更改 Grid.BackgroundProperty,但它接受画笔......苹果和橙子!因此,我创建了一个
SolidColorBrush
静态资源并将其命名为 rootElementBrush。在 XAML 中,我将 Grid rootElement 的背景属性设置为该静态资源。最后,我修改了动画,因此现在它更改了SolidColorBrush
的颜色。简单的!Solved!
Here's an explanation:
My initial mistake was that I wanted to change the
Grid.BackgroundProperty
by assigning colors to it, but it accepts brushes instead... apples and oranges! So, I created aSolidColorBrush
static resource and named it rootElementBrush. In XAML, I setGrid rootElement
's background property to that static resource. And finally, I modified the animation, so now it changes the color for thatSolidColorBrush
. Easy!尝试一下:
Give this a try:
您不需要设置
StaticResource
,只需使用Storyboard
。You do not need to set the
StaticResource
, just use theStoryboard
.