Working with the Grid

Of all the panels provided with the WPF APIs, Grid is far and away the most flexible. Like an HTML table, the
Grid can be carved up into a set of cells, each one of which contains content. In many cases, the cells of a Grid will
contain other panel types (StackPanel, Canvas, etc). This allows you to build a very flexible layout system.

When defining a Grid, you perform three steps:
    •        Define each column in the grid.
    •        Define each row in the grid.
    •        Assign content to each cell of the grid using attached-property syntax.

Here is a grid consisting of four cells. For display purposes, the
ShowGridLines property has been set to true.


<Grid ShowGridLines = "True" Background = "AliceBlue">
<!-- Define the rows / columns. -->
<Grid.ColumnDefinitions>
  <ColumnDefinition/>
  <ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
  <RowDefinition/>
  <RowDefinition/>
</Grid.RowDefinitions>

<!-- Now add the elements to the grid's cells. -->
<TextBlock Name = "lblInstruction" Grid.Column = "0" Grid.Row = "0"
 FontSize = "15">Enter Car Information</TextBlock>
<Button Name = "btnOK"  Height = "30" Grid.Column = "0"
  Grid.Row = "0" Content="OK"/>
<TextBlock Name = "lblMake" Grid.Column = "1" Grid.Row = "0" Text="Make" />
<TextBox Name = "txtMake" Grid.Column = "1"
   Grid.Row = "0" Width = "193" Height = "25"/>
<TextBlock Name = "lblColor" Grid.Column = "0"
   Grid.Row = "1" >Color</TextBlock>
<TextBox Name = "txtColor" Width = "193" Height = "25"
   Grid.Column = "0" Grid.Row = "1" />

<!-- Just to keep things interesting,
   add some color to one cell.-->
<Rectangle Fill = "LightGreen" Grid.Column = "1" Grid.Row = "1" />
<TextBlock Name = "lblPetName" Grid.Column = "1"
       Grid.Row = "1" >Pet Name</TextBlock>
<TextBox Name = "txtPetName" Grid.Column = "1" Grid.Row = "1"
       Width = "193" Height = "25"/>
</Grid>
Stack Panel
Table of Contents
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services