Click here to Skip to main content
15,747,059 members
Articles / Desktop Programming / WPF
Posted 11 Apr 2010

Tagged as


2 bookmarked

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
22 May 2010CPOL
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.

/// <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);
    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.


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

Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

-- There are no messages in this forum --