我将一组控件存储在一个数组中,并试图在循环中一个接一个地为所有控件设置动画,但我只能看到最后一个控件的动画效果?
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;
}发布于 2010-12-08 21:56:03
我不知道该如何解释这种行为。如果没有Dispatcher.BeginInvoke,你只会让所有的项目同时淡出。然而,我不明白为什么您在使用BeginInvoke时不能得到相同的结果。然而,这两个都不是你想要的。您需要一个接一个地对动画进行排序。
最好的方法可能是使用带有多个动画的单个StoryBoard,动画的排序毕竟是Storyboard的全部要点。
private DoubleAnimation CreateAnimation(double from, double to, DependencyObject targetControl, int index)
{
DoubleAnimation animation = new DoubleAnimation();
animation.From = from;
animation.To = to;
animation.Duration = TimeSpan.FromSeconds(1);
animation.BeginTime = TimeSpan.FromSeconds(1 * index);
animation.AutoReverse = false;
Storyboard.SetTarget(animation, targetControl);
Storyboard.SetTargetProperty(animation, new PropertyPath(UIElement.OpacityProperty));
return animation;
}请注意额外的index参数,该参数用于指定动画应该何时开始。
现在你的代码很简单:
var sb = new Storyboard();
for (int i = 0; i < 4; i++)
{
sb.Children.Add(CreateAnimation(1.0, 0.0, this.Lights[0, i], i);
}
sb.Begin(); https://stackoverflow.com/questions/4384941
复制相似问题