Introduction to the WPF Grid Control

Grids work a little differently than tables do, and I was surprised as how it worked.  I think it's a better construct, but it can be a little  more verbose than to a table-like counterpart.  Let's look at it in more detail and you will see why.

A grid consists of rows and columns.  To setup this, use the following definition:

     <RowDefinition Height="Auto" />
     <RowDefinition Height="Auto" />
     <RowDefinition Height="Auto" />
     <ColumnDefinition Width="75" />
     <ColumnDefinition Width="Auto" />

A Grid has RowDefinitions and ColumnDefinitions that specify the height (specific to the row), the width (specific to the column), and possibly other dimensional aspects.  Normally, you would expect to see a combination of row/cell or row/column objects to lay out the grid; however, WPF works differently.  Each control has a Grid.Row and Grid.Column, which specifies the row/column to render in.

For instance, a <TextBox Grid.Row="1" Grid.Column="1" /> Renders in row 1, column 1 of the grid.  Multiple controls can render in a grid in this way.  This may seem a little odd at first, but in actuality it is very practical to setup the grid this way.  Controls must be within the grid to setup them in the grid though, so make sure they are setup as children.

Grids can also setup column/row spanning, as shown in the button at the bottom of the next complete example.  This works like in HTML, with the colspan or rowspan attributes.  A complete setup example is shown below:

<Label Grid.Row="0" Grid.Column="0" Width="50">Item 1:</Label>
<TextBox Name="Item1" Grid.Row="0" Grid.Column="1" Width="50" />
<Label Grid.Row="1" Grid.Column="0" Width="50">Item 2</Label>
<TextBox Name="Item2" Grid.Row="1" Grid.Column="1" Width="50" />

<Button Name="ConnectButton" Content="Connect" Grid.ColumnSpan="2" Grid.Row="2" Click="OnConnectButtonClick" />

And within this, we have a form within the grid.  It's that simple; however, it gets confusing determining whether a 1 goes here, or a 0 goes there, and so setting it up takes a bit of thought.  In addition, you can see how someone used to HTML could be a little taken aback by this new approach; however, I believe it is an overall improvement.

Published Friday, July 27, 2007 9:19 PM by bmains
Filed under:


# How can we fast align a controls in a WPF window? - Adkerson

Wednesday, September 10, 2014 6:57 PM by How can we fast align a controls in a WPF window? - Adkerson

Pingback from  How can we fast align a controls in a WPF window? - Adkerson