Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autosizing a grid column to take up remaining space in parent

Tags:

wpf

grid

In WPF, I am having a heck of a time trying to get a grid to size properly.

I have the following layout for my grid:

<ItemsControl HorizontalContentAlignment="Stretch">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto"/>
                        <ColumnDefinition Width="80"/>
                        <ColumnDefinition Width="80"/>
                        <ColumnDefinition Width="100"/>
                    </Grid.ColumnDefinitions>
                    <Label Grid.Column="0" />
                    <Label Grid.Column="1"/>
                    <TextBox Grid.Column="2"/>
                    <Button Grid.Column="3"/>
                </Grid>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

The problem is that Width="Auto" seems to be sizing that column to the width of the content, and not filling out the extra space in the parent container. This leaves the rest of the columns all unaligned, and ugly blank space at the end of each row.

I'm probably missing something simple, but I can't seem to find a method to fit the column appropriately.

Or is there a better control for the job?

like image 695
Justin Mathieu Avatar asked Sep 14 '12 21:09

Justin Mathieu


People also ask

How do you change the width of a grid column?

You can specify the width of a column by using a keyword (like auto ) or a length (like 10px ). The number of columns is determined by the number of values defined in the space-separated list.


2 Answers

* means fill or share. If you had two with * then they would share the width evenly.

<ColumnDefinition Width="*"/>
like image 83
paparazzo Avatar answered Oct 15 '22 07:10

paparazzo


Seems I found a solution after a bit more tinkering around.

The problem was: <ColumnDefinition Width="Auto"/>

This was causing the column to fit to the content. I changed it to: <ColumnDefinition />

This causes the column to fit to the empty space left in the parent container, regardless of content size.

like image 1
Justin Mathieu Avatar answered Oct 15 '22 07:10

Justin Mathieu