WPF Two Grid Columns the Same Size


You can force two columns, or rows, in a WPF Grid Panel to be the same size. How do you do that? Use the SharedSizeScope and SharedSizeGroup properties. When defining the columns (or rows) use SharedSizeGroup and use SharedSizeScope when defining the Grid.

Note that if you use “Auto” for the Width property, the content will define the width. The width will be just wide enough to accommodate the content. We will look at examples to show this.

True

Below is the XAML code for the screenshot above. Notice that we’ve set the Grid.IsSharedSizeScope to True and that the two rows that we want to be the same have the property SharedSizeGroup equal to a string that is the same. In this case, it is “B”. We could have used any string here just as long as the strings are the same.

    <Grid Name="aGrid" Grid.IsSharedSizeScope="True">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="B"/>
            <ColumnDefinition />
            <ColumnDefinition Width="Auto" SharedSizeGroup="B"/>
        </Grid.ColumnDefinitions>
        
        <!-- 0,0 does not need Grid.Row or Grid.Column because default is 0 -->
        <Label Content="0,0" Background="Coral" /> 
        <Label Content="1,0" Background="Moccasin" Grid.Row="1" />
        <Label Content="Row 0 Col 2" Background="Lavender" Grid.Column="1" />
        <Label Content="Row 1 Col 2" Background="LemonChiffon" Grid.Row="1" Grid.Column="1" />
        <Label Content="Row 0 Col 3" Background="LightSalmon" Grid.Column="2" />
        <Label Content="Row 1 Col 3" Background="GreenYellow" Grid.Row="1" Grid.Column="2" />
    </Grid>

False

Here is another example where the difference is that we have changed the setting to False: Grid.IsSharedSizeScope=”False”. Since column 3 is Auto, it only uses as much as it needs The rest of the space is shared between the first two columns.

Below is the only change we made to the code above. It is now False.

    <Grid Name="aGrid" Grid.IsSharedSizeScope="False">

True, but with Auto moved over

Let’s make the first and third the same width again by setting the property to True. If we change the Auto for the width from the third to the first column, we get the same results as the first screenshot at this post. It works, but it is a better code format to put the “Auto” in the wider column if you know which one is wider. Here below is a partial listing of the code that results in the same output as the first screenshot above.

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" SharedSizeGroup="B"/>
            <ColumnDefinition />
            <ColumnDefinition SharedSizeGroup="B"/>
        </Grid.ColumnDefinitions>