我见过其他类似的问题,但他们似乎总是在 XAML 中这样做,因为这是在事件处理程序中,我需要在 C# 中找出答案。基本上我只需要发送菜单项闪烁红色。
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 中还是在代码隐藏中:
var item = (MenuItem)sender;
item.Foreground = new SolidColorBrush(Colors.Black);
item.Foreground.BeginAnimation(SolidColorBrush.ColorProperty, ca);
如果您从当前颜色值(例如此处的 Black
)设置动画,则不必设置动画的 From
属性。
另请注意,您不应在未检查结果是否为 null
的情况下使用 as
运算符。最好使用显式类型转换而不是 as
,因为如果 sender
不是 MenuItem
,您将正确获得 InvalidCastException
而不是 NullReferenceException
。
关于c# - 无法为颜色属性设置动画,因为对象已密封或卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40358884/