Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying Grid Star Size in code behind

Tags:

c#

wpf

How do I construct this piece of XAML programatically?

<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>

Is it any elegant solution for parse and construct controls dynamically?

I was trying to do something:

RowDefinition newRow = new RowDefinition();
newRow.Height = new GridLength(10);
newGrid.RowDefinitions.Add(newRow);

But how do I assign a * sign?

Looking for any kind of ideas to this problem! Thanks!

like image 967
Wild Goat Avatar asked Feb 27 '12 14:02

Wild Goat


3 Answers

You can use the Grid.Star unit type

newRow.Height = new GridLength(1, GridUnitType.Star);

You can also use the XamlReader object to convert XAML strings into UI objects from code-behind, although I usually prefer to manually create objects like how you are creating them.

like image 110
Rachel Avatar answered Nov 23 '22 21:11

Rachel


Here are some examples:

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});

and similarly for columns.

like image 29
Phil Avatar answered Nov 23 '22 21:11

Phil


Using the GridLength constructor that allows you to specify GridUnitType is the right approach here, as others suggested.

But if, for some reason, you want to actually convert the string value to the correct type the same way it's done in XAML, you can do that too:

Look at the GridLength type: it has defined the TypeConverter attribute with the parameter typeof(GridLengthConverter). This means you can use that type to perform the conversion:

new GridLengthConverter().ConvertFromString("*")
like image 33
svick Avatar answered Nov 23 '22 22:11

svick