在代码中指定RowDefinition.Height

And*_*ndy 15 c# wpf grid xaml

当您在xaml中创建网格时,您可以定义RowDefinitions

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
</Grid>
Run Code Online (Sandbox Code Playgroud)

我需要在代码中做同样的事情.我知道我可以写

RowDefinition row = new RowDefinition();
row.Height = new GridLength(1.0, GridUnitType.Star);
Run Code Online (Sandbox Code Playgroud)

但这并没有帮助我,因为我有一个字符串进来.我可能会创建自己的"字符串到GridLength"转换器,但这感觉不对,因为它从xaml工作如此顺利.当然,我尝试了以下但是它不起作用

row.Height = new GridLength("*");
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

Fre*_*lad 15

GridLength结构有一个TypeConverter定义在XAML实例化时正在被使用.您也可以在代码中使用它.它被称为GridLengthConverter

如果你看一下GridLength.csReflector它看起来像这样.请注意TypeConverter

[StructLayout(LayoutKind.Sequential), TypeConverter(typeof(GridLengthConverter))]
public struct GridLength : IEquatable<GridLength>
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

你可以像使用它一样

GridLengthConverter gridLengthConverter = new GridLengthConverter();
row.Height = (GridLength)gridLengthConverter.ConvertFrom("*");
Run Code Online (Sandbox Code Playgroud)


H.B*_*.B. 10

无需创建转换器,已经存在一个转换器,XAML解析器也在使用它:

var converter = new GridLengthConverter();
row.Height = (GridLength)converter.ConvertFromString("*");
Run Code Online (Sandbox Code Playgroud)

在旁注中,您会发现很多类型的转换器,因为许多类型都是从XAML中的字符串中解析出来的,例如BrushConverter&ImageSourceConverter


小智 9

您缺少将RowDefinition包含在RowDefinitions中

RowDefinition row = new RowDefinition();
row.Height = new GridLength(1.0, GridUnitType.Star);
YourGrid.RowDefinitions.Add(row);
Run Code Online (Sandbox Code Playgroud)

再见!Rutx