Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

Setting non-numeric grid row/column sizes in WPF/Silverlight

5.00/5 (4 votes)
22 May 2010CPOL 1  
Programatically set grid row/column sizes (yes, even Auto, *, and X* - thanks Nish).
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.

XML
//--------------------------------------------------------------------------------
/// <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.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)