Set Grid Column/Row width/Height dynamically
Asked Answered
B

4

23

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 ?

Burgett answered 15/3, 2012 at 13:46 Comment(0)
J
32

You could specify it like this:

For auto sized columns:

GridLength.Auto

For star sized columns:

new GridLength(1,GridUnitType.Star)
Jus answered 15/3, 2012 at 13:50 Comment(0)
J
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!

Jim answered 27/2, 2015 at 9:22 Comment(0)
P
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

Paper answered 15/3, 2012 at 14:1 Comment(0)
A
-1

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

Abisia answered 29/2 at 20:12 Comment(1)
Please consider the usefulness of your answer to all users before posting, including those who are unable to view images.Mustard

© 2022 - 2024 — McMap. All rights reserved.