WPF Grid: ‘Auto’ vs ‘*’

For some reason every time I use a Grid control in WPF, I get these two settings mixed up.  The difference is subtle but simple, and it has a huge impact on how your content is displayed. 

The important thing to remember is that ‘Auto’ will size the row or column based on its content, while ‘*’ will size the row or column based on the size of the Grid.

Setting the Height or Width to ‘*’

Setting the height or width of a column or row to ‘*’ will force the row or column to fill any “empty” space until the width or height of all the rows and columns is equal to the width or height of the grid.  For example, if you define a grid with the following rows:

<Grid.RowDefinitions>
	<RowDefinition Height="40"/>
	<RowDefinition Height="*"/>
</Grid.RowDefinitions>

This will result in a second row that expands vertically to the height of the grid, minus the first row height. 

If instead, both rows are given a height of ‘*’:

<Grid.RowDefinitions>
	<RowDefinition Height="*"/>
	<RowDefinition Height="*"/>
</Grid.RowDefinitions>

The rows will both expand vertically to fill the Grid.  Each subsequent ‘*’ is sized so that the heights of all the rows exactly equal the height of the Grid, and each ‘*’ height is equal to the others. 

Finally, you can define how each height or width relates to the others by specifying a factor:

<Grid.RowDefinitions>
	<RowDefinition Height="*"/>
	<RowDefinition Height="2*"/>
</Grid.RowDefinitions>

In this case, the second row will be twice as tall as the first, subject to the same constraints as before.

Setting the Height or Width to ‘Auto’

Setting a height or width to ‘Auto’ results in a row or column that will size itself based on its content.  If you defined the following columns:

<Grid.ColumnDefinitions>
	<ColumnDefinition Width="120"/>
	<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>

The second column’s width would be entirely based on the width of its contents.  If you had the following content:

<Button Width="80" Grid.Column="0"/>
<Button Width="80" Grid.Column="1"/>

The first column would still have a width of 120, while the second column would only have a width of 80.  Notice that it does not matter how wide the Grid itself is.  ‘Auto’ will always size itself to fit the size of its content.