I am trying to change the opacity of a rectangle from 0 to 1 and back from 1 to 0, but also to wait 2 seconds at every step. so i want 2 seconds to be 1, after that to change it to 0 in 500 milliseconds and then wait another 2 seconds with the opacity 0 and going again in 500 milliseconds to 1 and so one.
I have this code:
Storyboard.SetTargetProperty(forwardDoubleAnimation,
new PropertyPath("(Path.Fill).(SolidColorBrush.Opacity)"));
Storyboard.SetTargetProperty(reverseDoubleAnimation,
new PropertyPath("(Path.Fill).(SolidColorBrush.Opacity)"));
forwardDoubleAnimation.Completed += (sender, args) =>
{
Thread.Sleep(2000);
reverseStoryboard.Begin();
};
reverseDoubleAnimation.Completed += (sender, args) =>
{
Thread.Sleep(2000);
forwardStoryboard.Begin();
};
But i have an exception on reverseStoryboard.Begin() that says i didn't set a target property for it.
Is there a way to do it using a single animation and to set a property in order to wait?
You may take advantage from the fact that, although an Opacity has values in the range 0 to 1, you may set values lower than 0 or greater than 1.
If you animate an Opacity from -2 to 3 in 2.5 second, in the first second it goes from -2 to 0, which is 0 effectively, then it goes from 0 to 1 in 0.5 seconds, then from 1 to 3, i.e. effectively 1 in another second.
var animation = new DoubleAnimation
{
From = -2,
To = 3,
Duration = TimeSpan.FromSeconds(2.5),
AutoReverse = true,
RepeatBehavior = RepeatBehavior.Forever
};
rectangle.Fill.BeginAnimation(Brush.OpacityProperty, animation);