WPF Control Layout
(Page 1 of 5 )
One of the most important decisions when designing a WPF application is how to lay out the application's controls. Controls need to be put in the application in a way that makes sense and makes the application easy to use. Control placement is facilitated through a number of layout elements, such as Grid and StackPanel. Using these, developers can easily lay out controls to achieve the desired look. WPF offers several layout elements designed for various purposes, and in this article, we'll take a look at each of them.
Note that the examples in this article are all created as part of browser-hosted applications for the purpose of taking simple screenshots. Furthermore, the dimensions of the pages may be modified in order to make the result small and visually appealing, or to show off a particular feature (e.g. wrapping with the WrapPanel).
Canvas
We'll start by looking at the Canvas control. This control is a bit unique in that it doesn't arrange its children controls in any way. Rather, each child can be positioned individually using an absolute positioning system. So, in one light, Canvas can be seen as primitive, and in another light, it can be seen as flexible, since you're not confined to a particular layout scheme when using it. The Canvas control, then, can be used to create some fancy applications.
Here's an example of an interesting layout that can be created with Canvas:

You can arrange controls by specifying their Canvas.Top, Canvas.Left, Canvas.Bottom, and Canvas.Right attributes, which map to positions on the canvas. Canvas.Top specifies the distance from the top of the Canvas, Canvas.Left specifies the distance from the left side of the Canvas, Canvas.Bottom specifies the distance from the bottom of the Canvas, and Canvas.Right specifies the distance from the right side of the canvas. So, a control with a Left value of 10 and a Top value of 20 would have its top left corner 10 pixels from the left side of the Canvas and 20 pixels from the top of the canvas. The above layout, then, can be created like this:
<Canvas>
<Button Canvas.Left="10" Canvas.Top="10"
Content="Button 1" />
<Button Canvas.Left="60" Canvas.Top="60"
Content="Button 2" />
<Button Canvas.Left="110" Canvas.Top="110"
Content="Button 3" />
<Button Canvas.Left="60" Canvas.Top="160"
Content="Button 4" />
<Button Canvas.Left="10" Canvas.Top="210"
Content="Button 5" />
</Canvas>
Above, Canvas.Left and Canvas.Top are specified. However, let's use Canvas.Right and Canvas.Bottom to create a mirror image:

<Canvas>
<Button Canvas.Right="10" Canvas.Bottom="210"
Content="Button 1" />
<Button Canvas.Right="60" Canvas.Bottom="160"
Content="Button 2" />
<Button Canvas.Right="110" Canvas.Bottom="110"
Content="Button 3" />
<Button Canvas.Right="60" Canvas.Bottom="60"
Content="Button 4" />
<Button Canvas.Right="10" Canvas.Bottom="10"
Content="Button 5" />
</Canvas>
Next: StackPanel >>
More Windows Scripting Articles
More By Peyton McCullough