由于对象已密封或冻结,因此无法设置颜色属性的动画 [英] Cannot animate the color property because the object is sealed or frozen

查看:113
本文介绍了由于对象已密封或冻结,因此无法设置颜色属性的动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过其他类似的问题,但是他们似乎总是在XAML中这样做,因为这是在事件处理程序中,所以我需要在c#中找出答案.基本上,我只需要发送菜单项闪烁红色即可.

Ive seen other similiar issues but they alwayse seem to be doing this in XAML, since this is in an event handler I need to figure out the answer in c#. basically I just need the sending menu item to blink red.

ColorAnimation ca = new ColorAnimation()
{
    From = Color.FromRgb(0, 0, 0),
    To = Color.FromRgb(255,0,0),
    AutoReverse = true,
    RepeatBehavior = new RepeatBehavior(3),
    Duration=new Duration(TimeSpan.FromSeconds(.5))
};
(sender as MenuItem).Foreground.BeginAnimation(SolidColorBrush.ColorProperty, ca);

推荐答案

您必须先在元素的Foreground属性中为其分配可变的SolidColorBrush实例,然后才能在XAML或后面的代码中对其进行动画处理:/p>

You would have to assign a mutable SolidColorBrush instance to the element's Foreground property before it can be animated, either in XAML or in code behind:

var item = (MenuItem)sender;
item.Foreground = new SolidColorBrush(Colors.Black);
item.Foreground.BeginAnimation(SolidColorBrush.ColorProperty, ca);

如果从当前颜色值(例如此处的Black)进行动画处理,则不必设置动画的From属性.

If you animate from the current color value (e.g. Black here), you don't have to set the From property of the animation.

还请注意,如果不检查结果是否为null,则不应使用as运算符.最好使用显式类型强制转换而不是as,因为如果sender不是MenuItem,则可以正确获取InvalidCastException而不是NullReferenceException.

Note also that you shouldn't use the as operator without checking whether the result is null. Better use an explicit type cast instead of as, because in case sender is not a MenuItem, you would correctly get an InvalidCastException instead of a NullReferenceException.

这篇关于由于对象已密封或冻结,因此无法设置颜色属性的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆