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!
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.
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.
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("*")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With