How to Use the Grid Control in WPF

This article will demonstrate how to set up a WPF Grid control in XAML using Microsoft Visual Studio 2008. I apologize for the poor formatting of the XAML, but eHow does not have any support for formatting code. Copy the code into your editor and replace all occurrences of < with < to view the code properly. The Resources section below contains links to WPF books that I would recommend.

Things You'll Need

  • Microsoft Visual Studio 2008
Show More

Instructions

    • 1
      Code for Step 1

      Create a new WPF application in Visual Studio 2008. By default, the top level control will be a Grid. The generated XAML will look something like this:

      <Window x:Class="GridSample.Window1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Window1" Height="300" Width="300">
      <Grid>
      </Grid>
      </Window>

    • 2
      Code for Step 2

      Create a 2x2 grid using row and column definitions:

      <Grid>
      <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
      <ColumnDefinition></ColumnDefinition>
      <ColumnDefinition></ColumnDefinition>
      </Grid.ColumnDefinitions>
      </Grid>

    • 3
      Code for Step 3

      Add content to the grid cells:
      <Grid>
      <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
      <ColumnDefinition></ColumnDefinition>
      <ColumnDefinition></ColumnDefinition>
      </Grid.ColumnDefinitions>
      <TextBlock Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Text="TextBlock 1" Background="AliceBlue" />
      <TextBlock Grid.Row="0" Grid.Column="1" Text="TextBlock 2" Background="LightGray" />
      <TextBlock Grid.Row="1" Grid.Column="1" Text="TextBlock 3" Background="LightGreen" />
      </Grid>

      Grid.Row and Grid.Column specify where to place the content in the grid. Grid.RowSpan specifies the height of the content in rows. You can also use Grid.ColumnSpan to specify a width in columns.

    • 4

      Run the application and you should get something that looks like the image in this step.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured