Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic ColumnDefinitions with relative width values?

Tags:

c#

dynamic

wpf

grid

I have found code like this for dynamically creating a Grid and some columns:

Grid grd = new Grid();
ColumnDefinition c = new ColumnDefinition(); 
c.Width = new GridLength(50, GridUnitType.Pixel); 
. . .
grd.ColumnDefinitions.Add(c);

But I want to create columns with relative widths, that correspond to the "*"s used in xaml:

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

How can I use these relative width values/ratios dynamically?

like image 612
B. Clay Shannon-B. Crow Raven Avatar asked Feb 15 '12 20:02

B. Clay Shannon-B. Crow Raven


1 Answers

OK, I figured it out, right after posting the question:

. . .
ColumnDefinition c1 = new ColumnDefinition();
c1.Width = new GridLength(1, GridUnitType.Star);
ColumnDefinition c2 = new ColumnDefinition();
c2.Width = new GridLength(4, GridUnitType.Star);
ColumnDefinition c3 = new ColumnDefinition();
c3.Width = new GridLength(1, GridUnitType.Star);
ColumnDefinition c4 = new ColumnDefinition();
c4.Width = new GridLength(3, GridUnitType.Star);
ColumnDefinition c5 = new ColumnDefinition();
c5.Width = new GridLength(1, GridUnitType.Star);
. . .
grd.ColumnDefinitions.Add(c1);
. . .
like image 60
B. Clay Shannon-B. Crow Raven Avatar answered Nov 02 '22 05:11

B. Clay Shannon-B. Crow Raven