I've started working on a Silverlight application at work, and I had the need to create a
Grid
control programatically. If you've done any of this yourself, you know that you can set a row height or column width to either "Auto", "*", or a numeric pixel value (in your control's XAML). It took me a bit of time to find the answer on the web, and I ended up with the following method.
//--------------------------------------------------------------------------------
/// <summary>
/// Creates and returns a row definition object.
/// </summary>
/// <param name="height">The desired height attribute</param>
/// <returns>A RowDefinition object</returns>
private RowDefinition MakeRowDefinition(string height)
{
RowDefinition rowDef = new RowDefinition();
switch (height.ToLower())
{
case "auto" : rowDef.Height = new GridLength(1, GridUnitType.Auto); break;
case "*" : rowDef.Height = new GridLength(1, GridUnitType.Star); break;
default :
{
double pixels;
if (!Double.TryParse(height, out pixels))
{
throw new Exception("Invalid row definition pixel value.");
}
rowDef.Height = new GridLength(pixels, GridUnitType.Pixel);
}
break;
}
return rowDef;
}
The secret is the GridLength object, and after searching on google for the answer, I realized that Intellisense would have provided the answer I needed. You can extend this method to include other grid properties, but my only requirement was for row height, so I stopped there.