3

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);
Clemens
  • 123,504
  • 12
  • 155
  • 268
Wobbles
  • 3,033
  • 1
  • 25
  • 51

1 Answers1

7

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.

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • The as isnt a concern for me as the event handler is only called from a menu item and not reused for anything else. But your answer where I have to explicitly set the color AGAIN prior to animating worked perfect, any explanation as to why? – Wobbles Nov 01 '16 at 12:07
  • It is of course sufficient to set the Background once before animating it for the first time. You might probably do that in XAML. It is however important not to use one of the predefined Brushes like `Brushes.Black`, because these aren't mutable. – Clemens Nov 01 '16 at 12:12
  • ahh, weird, but makes sense I guess. – Wobbles Nov 01 '16 at 20:51