Specifying RowDefinition.Height in code
Asked Answered
B

4

17

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?

Businessman answered 31/8, 2011 at 22:30 Comment(0)
D
20

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

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>
{
    //...
}

You can use it like

GridLengthConverter gridLengthConverter = new GridLengthConverter();
row.Height = (GridLength)gridLengthConverter.ConvertFrom("*");
Doradorado answered 31/8, 2011 at 22:33 Comment(0)
Z
14

you are missing to include your RowDefinition to RowDefinitions

RowDefinition row = new RowDefinition();
row.Height = new GridLength(1.0, GridUnitType.Star);
YourGrid.RowDefinitions.Add(row);

See you! Rutx

Zenger answered 28/2, 2013 at 9:48 Comment(0)
A
11

No need to create a converter, there already is one, which is being used by the XAML-parser as well:

var converter = new GridLengthConverter();
row.Height = (GridLength)converter.ConvertFromString("*");

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

Alost answered 31/8, 2011 at 22:32 Comment(1)
Thanks, never heard of Type Converters before. Had to pick an answer and your didnt compile since GridLength is not nullable so.. Thanks for the tip of the other converters as wellBusinessman
T
0

Following Rutx answer I would make it even shorter

grdLbx.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1.0, GridUnitType.Star) });
Thermosiphon answered 10/10, 2023 at 8:50 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.