在代码后面应用Grid Star Size

Wil*_*oat 14 c# wpf

如何以编程方式构造这段XAML?

<Grid Name="gridMarkets">
    <Grid.RowDefinitions>
        <RowDefinition Height="10" />
        <RowDefinition Height="*" MinHeight="16" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
 </Grid>
Run Code Online (Sandbox Code Playgroud)

它是动态解析和构造控件的优雅解决方案吗?

我想做点什么:

RowDefinition newRow = new RowDefinition();
newRow.Height = new GridLength(10);
newGrid.RowDefinitions.Add(newRow);
Run Code Online (Sandbox Code Playgroud)

但是我该如何指定*标志?

寻找任何一种想法来解决这个问题!谢谢!

Rac*_*hel 39

您可以使用Grid.Star单位类型

newRow.Height = new GridLength(1, GridUnitType.Star);
Run Code Online (Sandbox Code Playgroud)

您也可以使用XamlReader对象将XAML字符串从代码隐藏转换为UI对象,尽管我通常更喜欢手动创建对象,就像创建它们一样.

  • @WildGoat默认单位是当你使用`Height ="*"`是1.这意味着该行将占用与所有其他星号行相等的空间.例如,如果你有两行都有'Height ="*"`,那么两行都会占用相同的空间.如果第一行有'Height ="2*"`,那么它将是第二行的两倍.如果Row1的'Height ="2*"`并且Row2的'Height ="3*"`,则第1行将占用可用空间的2/5,第2行将占用3/5. (4认同)
  • 如果您想要一颗星,那么您需要指定您想要一颗星,而不是零颗星。如果您不知道,您也可以在 XAML 中使用多个星号:例如 `Height="2*"`。 (2认同)

Phi*_*hil 8

这里有些例子:

grid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(10)});
grid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star), MinHeight = 16});

grid.RowDefinitions.Add(new RowDefinition {Height = new GridLength(1, GridUnitType.Star)});
grid.RowDefinitions.Add(new RowDefinition {Height = GridLength.Auto});
Run Code Online (Sandbox Code Playgroud)

对于列也是如此.


svi*_*ick 5

正如其他人所建议的那样GridLength,使用允许您指定的构造函数GridUnitType是正确的方法.

但是,如果由于某种原因,您希望实际上将字符串值转换为正确的类型,就像在XAML中完成一样,您也可以这样做:

查看GridLength类型:它已TypeConverter使用参数定义了属性typeof(GridLengthConverter).这意味着您可以使用该类型执行转换:

new GridLengthConverter().ConvertFromString("*")
Run Code Online (Sandbox Code Playgroud)