WPF Grid Panel


WPF provides five main built-in layout panels. Here is the list in order of complexity and general usefulness.

The Grid panel provides us with rows and columns, like an HTML table provides rows and columns. The Grid is very versatile and it is used often. In fact, when you create a new project in Visual Studio, you get a Grid by default. Let’s create a 2 x 2 grid. They are indexed starting with zero.

<Window x:Class="GridPanel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:GridPanel"
        mc:Ignorable="d"
        Title="GridPanel Example 1" Height="150" Width="350" MinHeight="150" MinWidth="350">
    <Grid Background="LightBlue">
        <!-- Define two rows and two columns -->
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
    </Grid>
</Window>

Let’s do a little bit more to show just a couple of things you can do with the grid panel before we on to more examples.

    <Grid Background="LightBlue">
        <!-- Define two rows and two columns -->
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <StackPanel Background="Blue">
            <Label    Grid.Row="0" Grid.Column="0" Foreground="White" FontWeight="Bold"
            HorizontalContentAlignment="Center">Welcome</Label>
            <Label    Grid.Row="0" Grid.Column="0" Foreground="Yellow"
            HorizontalContentAlignment="Center">Row 0 Column 0</Label>
        </StackPanel>
        <StackPanel Grid.Row="0" Grid.Column="1">
            <Button Name="btn1">a button</Button>
            <Button Name="btn2">another button</Button>
            <Button Name="btn3">button three</Button>
            <Button Name="btn4">button 4</Button>
        </StackPanel>
        <GroupBox Margin="10" Grid.Row="1" Grid.Column="0" Background="White" Header="A List:">
            <ListBox>
                <ListBoxItem Name="lbi1">Program 1</ListBoxItem>
                <ListBoxItem Name="lbi2">Program 2</ListBoxItem>
                <ListBoxItem Name="lbi3">Program 3</ListBoxItem>
            </ListBox>
        </GroupBox>
    </Grid>

Below is how our program looks when running.