Layout Basics
Layout in WPF is managed by panels. A panel is a special-purpose
user-interface element whose job is to arrange the elements it contains. The
type of panel you choose determines the style of UI layout within that panel.
Table 2-1 describes the main panel types built into WPF. Whichever
panel you use, the same basic rule always applies: an element's position is
always determined by the containing panel. Some panels also manage the size of
their children.
Table 2-1. Main panel types
|
Panel type
|
Usage
|
DockPanel
|
Allocates an entire edge of
the panel area to each child; useful for defining the rough layout of simple
applications at a coarse scale.
|
StackPanel
|
Lays out children in a
vertical or horizontal stack; extremely simple, useful for managing small scale
aspects of layout.
|
Grid
|
Arranges children within a
grid; useful for aligning items without resorting to fixed sizes and positions.
The most powerful of the built-in panels.
|
Canvas
|
Performs no layout logicputs
children where you tell it to; allows you to take complete control of the
layout process.
|
Using a panel is simple: just put the children you need to lay
out inside it. Example 2-1 shows
several elements inside a StackPanel.
Example 2-1. Simple StackPanel layout
<StackPanel Orientation="Vertical">
<TextBlock>This is some text</TextBlock>
<Button>Button</Button>
<Button>Button (different one)</Button>
<CheckBox>Check it out</CheckBox>
<TextBlock>More text</TextBlock>
</StackPanel>
This StackPanel arranges the children into a column, or stack,
as Figure 2-1 shows.
In this example, the child elements
inside the panel are oblivious to the way in which they are being arranged. We
could flip from a vertical to a horizontal layout without changing any of the
children by changing the StackPanel's Orientation attribute
from Vertical to Horizontal:
<StackPanel Orientation="Horizontal">
...as before
The elements will now be arranged in a horizontal line, as shown
in Figure 2-2.
The child elements are not always completely passivethey will
often want to influence the way in which the parent arranges them. For example,
setting a child's Width or Height properties overrides the
size that the parent would have chosen. Also, most of the built-in panel types
offer a range of ways in which child elements can indicate to the panel what
their requirements are. For example, if you set the DockPanel
.Dock property to Left on a child of a DockPanel,
the panel will put that child on the left. Nonetheless, it is always ultimately
the panel that decides the children's positions. Let's look at the built-in
panels.
|