#1,047 – Setting the Size of a Grid’s Rows or Columns from Code

There are three ways to set the size of a row or a column in a Grid:

  • Auto – set height/width to fit the size of the contained element
  • numeric value – explicitly set height/width to specified number of device independent units (1/96th in)
  • * or n* – distribute remaining space proportionately

You can set row or column sizes from code for all three of these methods.

        private void Button_Click(object sender, RoutedEventArgs e)
            // Set to Auto
            myGrid.RowDefinitions[0].Height = GridLength.Auto;

            // Set explicit size
            myGrid.RowDefinitions[1].Height = new GridLength(35.0, GridUnitType.Pixel);

            // Set star sizing (proportional)
            myGrid.RowDefinitions[2].Height = new GridLength(1.0, GridUnitType.Star);
            myGrid.RowDefinitions[3].Height = new GridLength(2.0, GridUnitType.Star);

Before clicking the button, the row heights default to “*” (evenly spaced):
After executing the code shown above, the Grid looks like this:


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: