我见过其他类似的问题,但他们似乎总是在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);

最佳答案

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

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


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



另请注意,在不检查结果是否为as的情况下,不应使用null运算符。最好使用显式类型转换,而不要使用as,因为如果sender不是MenuItem,则可以正确获取InvalidCastException而不是NullReferenceException

07-28 02:38
查看更多