如何以编程方式构造这段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对象,尽管我通常更喜欢手动创建对象,就像创建它们一样.
这里有些例子:
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)
对于列也是如此.
正如其他人所建议的那样GridLength,使用允许您指定的构造函数GridUnitType是正确的方法.
但是,如果由于某种原因,您希望实际上将字符串值转换为正确的类型,就像在XAML中完成一样,您也可以这样做:
查看GridLength类型:它已TypeConverter使用参数定义了属性typeof(GridLengthConverter).这意味着您可以使用该类型执行转换:
new GridLengthConverter().ConvertFromString("*")
Run Code Online (Sandbox Code Playgroud)