在代码中指定 RowDefinition.Height
当您在 xaml 中创建 Grid 时,您可以定义 RowDefinitions,因此
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
我需要在代码中执行相同的操作。我知道我可以写,
RowDefinition row = new RowDefinition();
row.Height = new GridLength(1.0, GridUnitType.Star);
但这对我没有多大帮助,因为我收到了一个字符串。我可能可以创建自己的“字符串到 GridLength”转换器,但这感觉不太对,因为它从 xaml 工作得如此顺利。当然,我已经尝试过以下方法,但它不起作用
row.Height = new GridLength("*");
我在这里缺少什么?
When you're creating a Grid in xaml you can define the RowDefinitions as such
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
</Grid>
I have a need to do the same thing in code. I know I can write
RowDefinition row = new RowDefinition();
row.Height = new GridLength(1.0, GridUnitType.Star);
but that doesn't help me much since I've got a string coming in. I could probably create my own "string to GridLength" converter but this doesn't feel right since it works ever so smooth from xaml. Of course, I've tried the following but it doesn't work
row.Height = new GridLength("*");
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
GridLength
结构定义了一个TypeConverter
,从 Xaml 实例化时将使用该类型。您也可以在代码中使用它。它的名称为GridLengthConverter
如果您使用 Reflector 查看
GridLength.cs
,它看起来像这样。注意TypeConverter
您可以像这样使用它
The
GridLength
struct has aTypeConverter
defined which is being used when instantiated from Xaml. You can use it in code as well. It's calledGridLengthConverter
If you look at
GridLength.cs
with Reflector it looks like this. Notice theTypeConverter
You can use it like
您缺少将 RowDefinition 包含到 RowDefinitions 中,
再见!
芸香科
you are missing to include your RowDefinition to RowDefinitions
See you!
Rutx
无需创建转换器,已经有一个转换器,它也被 XAML 解析器使用:
顺便说一句,您会发现像这样的转换器适用于很多类型,因为许多类型都可以使用这样的转换器。从 XAML 中的字符串解析,例如
BrushConverter
&图像源转换器
No need to create a converter, there already is one, which is being used by the XAML-parser as well:
On a sidenote, you will find converters like this for a lot of types, as many get parsed from strings in XAML, e.g.
BrushConverter
&ImageSourceConverter
按照 Rutx 的回答,我会把它写得更短
Following Rutx answer I would make it even shorter