The WPF / Silverlight syntax is long and cumbersome. This blog post describe a simple attached property that allows you to specify row and column widths / heights as a simple comma separated list, e.g. RowDefinitions="Auto,,3*,,,,2*"
The Grid is probably one of the most useful and versatile layouts that Silverlight and WPF offers. However, if you hand craft your XAML, as I do, you will probably start to find the Grid markup for defining rows and columns to be verbose and cumbersome. If we look at the following example, which uses a mixture of Auto, Star and Pixel widths / heights:
Despite this being a simple example, the required row and column definitions are highly verbose:
To provide a simpler alternative, I have created attached properties, one for the column definitions, and the other for the rows. These attached properties allow you to specify the columns / rows as a comma separated list of heights and widths.
Using this technique, the above example becomes:
The comma separated list defines the widths / heights of each column / row. The number of items in this list defined the number of rows / column that are generated. This notation supports pixel, star and auto widths / heights. Also, if you want a row or column with the default size, just leave the value blank, i.e. a row definition of ",,," will create four rows of default height.
The code to achieve this is pretty simple, involving a couple of attached properties and string parsing in their changed event handlers. The complete code for the GridUtils class is given below, feel free to copy and paste it into your project:
The code which parses the row and column strings is also executed by the Visual Studio designer, so you can see your new rows / columns immediately. It also works just fine in WPF and Silverlight.
You can download example projects in both technologies: SimplfiedGrid.zip
(Thanks to Rob Newsome for coming up with this idea in the first place!)
Regards, Colin E.
Want to receive more insights?
If you enjoyed this blog post, why not subscribe to our mailing list
to receive Scott Logic content, news and insights straight to your inbox?
Sign up here.
I am CTO at Scott Logic and am a prolific technical author, blogger and speaker on a range of technologies.
My blog includes posts on a wide range of topics, including WebAssembly, HTML5 / JavaScript and data visualisation with D3 and d3fc. You'll also find a whole host of posts about previous technology interests including iOS, Swift, WPF and Silverlight.
I'm board member of FINOS, which is encouraging open source collaboration in the financial sector. I'm also very active on GitHub, contributing to a number of different projects.