Set Grid Column/Row width/Height dynamically

Welsh King picture Welsh King · Mar 15, 2012 · Viewed 50.1k times · Source

I need to create a WPF grid dynamically from code behind. This is going okay and I can do it so that I set the content widths but what I need to do is set them so that when i resize the window the controls are re sized dynamically

var col = new ColumnDefinition();
col.Width = new System.Windows.GridLength(200);
grid1.ColumnDefinitions.Add(col);

This will produce XAML

<Grid.ColumnDefinitions>
     <ColumnDefinition Width="200"></ColumnDefinition>
</Grid.ColumnDefinitions>

But what I need is to use a * or question mark ie.

<Grid.ColumnDefinitions>
     <ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>

But the WidthValue does not support a * or question mark a when creating from code behind ?

Answer

ionden picture ionden · Mar 15, 2012

You could specify it like this:

For auto sized columns:

GridLength.Auto

For star sized columns:

new GridLength(1,GridUnitType.Star)