I have a rectangle which want to move using Canvas.SetLeft(rect, x);
But I wanna make it look like a smooth transition (animation). Here’s the code snippet that’s supposed to do this:
void animate()
{
for (int a = 0; a < 10; a++)
{
MainWindow.current.Dispatcher.BeginInvoke(new Action(move));
x += 10;
Thread.Sleep(100);
}
}
void move()
{
Canvas.SetLeft(rect, x);
}
It seems very basic but I’m having trouble doing it. I want the thread to sleep for a little time, & then set the rectangle’s x to a new value. But instead, the thread sleeps for 30*10 milli seconds, then the rectangle moves right instantly by 10*10 units. I’m not able to get the animation effect I want. And I’m aware that I’ve called Sleep on the GUI thread but I don’t think that should affect the animation.
Instead of forcing your UI thread to sleep. I would suggest you to use the
Storyboard Animationprovided by WPF specially for this purpose. This link will get you started if its’s something new too you –http://vbcity.com/blogs/xtab/archive/2009/12/28/wpf-simple-animations-to-move-and-resize-elements-simultaneously.aspx