Programmatically setting the width of a grid column with * in WPF

user589195 picture user589195 · Mar 21, 2012 · Viewed 85.9k times · Source

I want to programmatically configure a wpf grid.

I want to be able to set a grid with 2 columns, the first taking up 20% of available space, the second taking up 80%. In xaml I would use the * operator but I cant work out how to do this programmatically.

In Xaml I would do:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition width="20*" />
    <ColumnDefinition width="80*" />
</Grid>

In code I want to do:

Grid grid = new Grid();
grid.ColumnDefinitions.Add( new ColumnDefinition(20*) );
grid.ColumnDefinitions.Add( new ColumnDefinition(80*) );

Please could someone advise.

Answer

Klaus78 picture Klaus78 · Mar 21, 2012
Grid grid = new Grid();
ColumnDefinition c1 = new ColumnDefinition();
c1.Width = new GridLength(20, GridUnitType.Star);
ColumnDefinition c2 = new ColumnDefinition();
c2.Width = new GridLength(80, GridUnitType.Star);
grid.ColumnDefinitions.Add(c1);
grid.ColumnDefinitions.Add(c2);