问题描述
当你在XAML中创建一个网格,你可以定义RowDefinitions这样
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);
但是这并不能帮助我很多,因为我有进来的字符串。我大概可以创建自己的字符串GridLength转换器,但这种感觉不对,因为它的作品曾经在XAML那么顺利。当然,我已经试过了,但之后它不工作
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?
推荐答案
的 GridLength
结构有一个的TypeConverter
定义为从实例化时使用的是哪个XAML。您可以在代码中使用它。这就是所谓的 GridLengthConverter
The GridLength
struct has a TypeConverter
defined which is being used when instantiated from Xaml. You can use it in code as well. It's called GridLengthConverter
如果你看看 GridLength.cs
与反射它看起来像这样。注意的TypeConverter
If you look at GridLength.cs
with Reflector it looks like this. Notice the TypeConverter
[StructLayout(LayoutKind.Sequential), TypeConverter(typeof(GridLengthConverter))]
public struct GridLength : IEquatable<GridLength>
{
//...
}
您可以使用它像
GridLengthConverter gridLengthConverter = new GridLengthConverter();
row.Height = (GridLength)gridLengthConverter.ConvertFrom("*");
这篇关于在代码中指定RowDefinition.Height的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!