Cannot animate the color property because the object is sealed or frozen

喜欢而已 提交于 2019-12-08 02:17:00

问题


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

回答1:


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

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


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.



来源:https://stackoverflow.com/questions/40358884/cannot-animate-the-color-property-because-the-object-is-sealed-or-frozen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!