Page 3 of 5
Bounce a ball
It is always difficult to find a good simple example and in this case you would certainly do things differently if you really wanted to implement a bouncing ball graphic.
However it is a good example, because I've seen beginners try to transfer this simple idea from say Windows Forms where it more or less works, with the help of DoEvents, to WPF/Silverlight where it simply doesn't.
So let's code a bounding rectangle the dumb way first. The form has a Canvas, a Button and the Canvas has a single Rectangle to display:
<Grid x:Name="LayoutRoot" Background="White">
The button's click event handler simply calls a method to do the work which in turn calls an Update routine to change the Rectangles position by adding a "velocity" term to its position:
int vx = 1;
int vy = 1;
private void button1_Click(object sender,
} while (true);
Notice that the infinite loop a sure sign that something isn't going to work on a single threaded UI - but with the addition of a DoEvents it does work in Windows Forms.
Think of the Work method in general as doing something complicated like solving a differential equation that takes a long time and then calling update to display the result.
In this case the update method is simply:
Canvas.GetLeft(rectangle1) + vx);
Canvas.GetTop(rectangle1) + vy);
You can see that the first two instructions move the position of the Rectangle and the two if statements check to see if it has reached the edge of the canvas. If it has the if statements simply reverse the appropriate velocity.
If you don't like the example consider the Work method doing some complex number crunching and then calling Update to display the intermediate result in an effort to show the user how things are developing.
Of course if you run this example nothing will happen.
Once you click the button the infinite loop starts to run and updates the UI objects but as the UI thread never gets a chance to do anything else the application locks.
It is worth emphasising here that if you do put a DoEvents in the loop everything works.
Many novice WPF programmers when they find themselves in this situation add something like:
in the hope that pausing the thread might give the UI time to update - again this doesn't work because the UI thread is the on that is put to sleep.
One solution that does work is to use a timer to run the the Update method. As long as the total time that the Update method takes to run is less than the timer tick rate you can use this to share the UI thread between computation and the UI. Sometimes this is a natural approach sometimes it isn't.