在for循环中动画wpf控件
问题描述:
我想实现一个动画,我将控件从一行移动到另一个使用for循环。在for循环中动画wpf控件
private void AnimateStoryBoard(int number)
{
Storyboard _currentStoryBoard = new Storyboard();
//Row Animation
Int32Animation newrowanimation = new Int32Animation();
newrowanimation.From = number;
newrowanimation.To = number+1;
newrowanimation.Duration = new TimeSpan(0, 0, 0, 0, 500);
Storyboard.SetTargetProperty(newrowanimation, new PropertyPath("(Grid.Row)"));
_currentStoryBoard.Children.Add(newrowanimation);
Storyboard.SetTarget(newrowanimation, myrectangle);
_currentStoryBoard.Begin();
}
,我使用
for (int i = 0; i < 10; i++)
{
AnimateStoryBoard(i);
}
现在调用它,当我运行此我希望动画去从1到2则2〜3,然后3到4 ... 9-10。然而,动画直接跳到9,然后是10.
另外我怎样才能做到这一点在XAML?,请注意,这里的数字10只是一个例子。数字必须来自代码隐藏,它会不断变化。
答
恕我直言,没有必要重新发明轮子:key frame animation也意味着用于这一目的。
因此,创建你需要的动画,可以使用类似:
Storyboard storyBoard = new Storyboard();
int gridRowLimit = 5; // here you can set how many rows your grid has
Int32AnimationUsingKeyFrames intKeyFrame = new Int32AnimationUsingKeyFrames();
intKeyFrame.Duration = new TimeSpan(0, 0, 0, 0, gridRowLimit * 500);
for (int i = 1; i < gridRowLimit; i++)
{
intKeyFrame.KeyFrames.Add(new DiscreteInt32KeyFrame(i));
}
Storyboard.SetTargetProperty(intKeyFrame, new PropertyPath("(Grid.Row)"));
Storyboard.SetTarget(intKeyFrame, yourControl);
storyBoard.Children.Add(intKeyFrame);
storyBoard.Begin();
我希望它能帮助。
+0
正是我想要的。谢谢 – Rohit
答
正如Alexander Clare在评论中提到的那样,您必须在故事板中设置几个动画。使用循环的解决方案不起作用,因为在运行循环时您的方法不会返回,因此UI线程将无法呈现故事板/动画引起的更改。
一个解决方案将是一个单个的Storyboard
实例,其中包含可变数量的动画(每行一个动画)。使用BeginTime
属性来错开动画。我建议你在这些动画之间使用从40ms到100ms的值(我不会低于20ms)。
在代码中,这将是这个样子:
private void AnimateStoryboard(int number)
{
// Create the storyboard that will be played
var storyboard = new Storyboard();
// Create the animation objects for each row change and add them to the storyboard
var currentBeginTime = TimeSpan.Zero;
for (var i = 0; i < number; i++)
{
var animation = new Int32Animation();
// Set all the properties that you set on your animation objects before, and additionally use BeginTime
animation.BeginTime = currentBeginTime;
storyboard.Children.Add(animation);
// Update the currentBeginTime to achieve the staggering effect
currentBeginTime += TimeSpan.FromMilliseconds(50);
}
// Finally, start the Storyboard to run all animations
storyboard.Begin();
}
哟,不要等到之前的动画才能开始下一个动画。这留下了最后的动画。您应该等待动画在循环内完成 –
这似乎与您之前询问的问题完全相同:https://stackoverflow.com/questions/44212995/repeating-storyboard-animation-using-for-loop 。不要删除和重新发布问题。 **解决您最初发布的问题。** –