21

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 ?

H.B.
  • 166,899
  • 29
  • 327
  • 400
Welsh King
  • 3,178
  • 11
  • 38
  • 60

3 Answers3

30

You could specify it like this:

For auto sized columns:

GridLength.Auto

For star sized columns:

new GridLength(1,GridUnitType.Star)
ionden
  • 12,536
  • 1
  • 45
  • 37
8

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!

Jamaxack
  • 2,400
  • 2
  • 24
  • 42
6

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

Max
  • 1,810
  • 3
  • 26
  • 37
Shounbourgh
  • 258
  • 2
  • 14