#1,047 – Setting the Size of a Grid’s Rows or Columns from Code
April 9, 2014 Leave a comment
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: