21
votes

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 ?

3

3 Answers

29
votes

You could specify it like this:

For auto sized columns:

GridLength.Auto

For star sized columns:

new GridLength(1,GridUnitType.Star)
8
votes

There is 3 types of setting Width to Grid ColumnDefinitions:

For Percentage Column:

 yourGrid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star); 

In xaml:

<ColumnDefinition Width="1*"/>

For Pixel Column

yourGrid.ColumnDefinitions[0].Width = new GridLength(10, GridUnitType.Pixel);
yourGrid.ColumnDefinitions[0].Width = new GridLength(10); 

In xaml:

<ColumnDefinition Width="10"/>

For Auto Column

yourGrid.ColumnDefinitions[0].Width = GridLength.Auto;

In xaml:

<ColumnDefinition Width="Auto"/>

Hope it helps!

6
votes

I think this can help:

for Auto Column:

ColumnDefinition cd = new ColumnDefinition();
cd.Width = GridLength.Auto;

or for proportion grid length:

ColumnDefinition cd = new ColumnDefinition();
cd.Width = new GridLength(1, GridUnitType.Star);

or look at: http://msdn.microsoft.com/en-us/library/system.windows.gridlength.aspx and http://msdn.microsoft.com/en-us/library/system.windows.gridunittype.aspx

Greez Shounbourgh