I have a canvas where i add more shapes programmatically. And for one of the shapes (a Path
) i want to add a fill color that will flicker at every second (change from red to blue and back).
I found an example on how to do that from xaml:
<Ellipse Fill="Red">
<Ellipse.Triggers>
<EventTrigger RoutedEvent="Ellipse.Loaded">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
Duration="0:0:2"
FillBehavior="HoldEnd"
RepeatBehavior="Forever">
<ColorAnimationUsingKeyFrames.KeyFrames>
<DiscreteColorKeyFrame KeyTime="0:0:0" Value="Red"/>
<DiscreteColorKeyFrame KeyTime="0:0:1" Value="Blue"/>
</ColorAnimationUsingKeyFrames.KeyFrames>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Ellipse.Triggers>
But when i do it from the code i receive an ArgumentNullException
: "{"Value cannot be null.\r\nParameter name: routedEvent"}"
This is my code:
var sheetPath = new Path
{
Stroke = Brushes.Black,
Fill = !isSelectedSheet ? Brushes.MediumSlateBlue : GetInvertedColor(Brushes.MediumSlateBlue),
StrokeThickness = _lineWidth,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Center,
Data = CreatePathGeometry(contour, height)
};
var colorAnimationUsingKeyFrames = new ColorAnimationUsingKeyFrames
{
Duration = new Duration(new TimeSpan(0, 0, 0, 300)),
RepeatBehavior = RepeatBehavior.Forever,
FillBehavior = FillBehavior.HoldEnd
};
colorAnimationUsingKeyFrames.KeyFrames.Add(new DiscreteColorKeyFrame
{
KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 100)),
Value = Colors.Red
});
colorAnimationUsingKeyFrames.KeyFrames.Add(new DiscreteColorKeyFrame
{
KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 200)),
Value = Colors.Blue
});
var storyboard = new Storyboard();
storyboard.Children.Add(colorAnimationUsingKeyFrames);
Storyboard.SetTargetProperty(storyboard.Children[0], new PropertyPath("(Path.Fill).(SolidColorBrush.Color)"));
var beginStoryboard = new BeginStoryboard();
beginStoryboard.Storyboard = storyboard;
var eventTrigger = new EventTrigger();
eventTrigger.Actions.Add(beginStoryboard);
sheetPath.Triggers.Add(eventTrigger);
canvas.Children.Add(sheetPath);