I am storing a set of controls in an array and i am trying to animate all the controls one by one in a loop but I can see only last one animating ?
for (int i = 0; i < 4; i++)
{
Dispatcher.BeginInvoke(() =>
{
var sb = new Storyboard();
sb = CreateStoryboard(1.0, 0.0, this.Lights[0, i]);
sb.Begin();
});
}
private Storyboard CreateStoryboard(double from, double to, DependencyObject targetControl)
{
Storyboard result = new Storyboard();
DoubleAnimation animation = new DoubleAnimation();
animation.From = from;
animation.To = to;
animation.Duration = TimeSpan.FromSeconds(1);
animation.BeginTime = TimeSpan.FromSeconds(1);
animation.AutoReverse = false;
Storyboard.SetTarget(animation, targetControl);
Storyboard.SetTargetProperty(animation, new PropertyPath(UIElement.OpacityProperty));
result.Children.Add(animation);
return result;
}
I’m at a loss to explain that behaviour. Without the
Dispatcher.BeginInvokeyou would just get all items fading at the same time. However I can’t see why you wouldn’t get the same when usingBeginInvoke. Still neither is what you are after. You need to sequence the animations one after another.Probably the best way to do this is to use a single StoryBoard with multiple animations, the sequencing of animations is afterall the whole point of a Storyboard.
Note the extra
indexparameter and that is use to specify when the animation should begin.Now your code is simply:-