C# · 12月 29, 2021

c# – 如何创建具有相对宽度值的动态ColumnDefinitions?

我已经找到这样的代码来动态创建一个网格和一些列: Grid Grd = new Grid();ColumnDeFinition c = new ColumnDeFinition(); c.Width = new GridLength(50,GridUnitType.Pixel); . . .Grd.ColumnDeFinitions.Add(c);

但是我想创建相对宽度的列,它们对应于xaml中使用的“*”:

<Grid.ColumnDeFinitions> <ColumnDeFinition Width=”*” /> <ColumnDeFinition Width=”*” /> <ColumnDeFinition Width=”*” /> <ColumnDeFinition Width=”4*” /> <ColumnDeFinition Width=”*” /> <ColumnDeFinition Width=”3*” /> <ColumnDeFinition Width=”*” /> <ColumnDeFinition Width=”*” /> </Grid.ColumnDeFinitions>

如何动态地使用这些相对宽度值/比例?

解决方法 好的,我想出来,发布后问题: . . .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);. . .