How Auto width Grid columns work with column spanning.

A friend of mine was wondering if he had encountered a bug in WPF today. What he was trying to do is have a Grid with four columns, each with a width of Auto, and have a TextBox fill the entire width of his Grid. Here was his Xaml.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="4" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>

What he wants is for his TextBox to take up the remaining width in the Grid. The way Auto works for a GridColumn‘s width, is that it sizes itself to the maximum width of its content. So in this case, the width of each column is that of the width of each button. Now because there are only four columns defined in the Grid, the TextBox can only span a maximum of four columns. The remainder of the Grid is undefined space that fills the Window, because the default behavior of a Grid is to fill its parent container.

So how do we get the TextBox to fill the undefined space? You define it. Add a fifth column with a * width, which means it will fill the remainder of the Grid space, and then we can set the TextBox to span all five columns, instead of the first four.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="5" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>

Leave a Comment

Your email address will not be published.