Welsh King
Welsh King

Reputation: 3238

Set Grid Column/Row width/Height dynamically

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 ?

Upvotes: 23

Views: 60005

Answers (4)

Hemendr
Hemendr

Reputation: 1060

A lot of explanations have already been provided by others. GridLength syntax is the same for both RowDefinations and ColumnDefinations. Sharing colour code syntax for quick and easy understanding
enter image description here

Upvotes: -1

Jamaxack
Jamaxack

Reputation: 2460

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!

Upvotes: 8

Shounbourgh
Shounbourgh

Reputation: 260

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

Upvotes: 6

ionden
ionden

Reputation: 12786

You could specify it like this:

For auto sized columns:

GridLength.Auto

For star sized columns:

new GridLength(1,GridUnitType.Star)

Upvotes: 33

Related Questions