One of the downsides of XAML is that it can become very verbose. A specific area where this happens is when using a
Grid and you start defining rows and columns. To overcome this, a change has been merged that will make your live (and XAML!) a whole lot easier. In this post you will learn how.
Grid Column and Row Definitions
Let’s first have a look at the “old” way. Of course, there is no old way, everything will still work as it did before, there is now just another way of doing this. Before you would probably define your grid something like this.
While this works just fine, you can imagine that when your layout starts growing, this will become unreadable.
Simplicity is Awesome
Then came this proposal. In the proposal we see how Morten suggests that the syntax will be simplified to a way where you can just specify all values in a comma-separated way. The column and row definitions are nothing more than a list of values, so it should be pretty easy to parse that.
When implemented, the same grid we saw above could now be reduced to this one line below.
That is amazing, right?! This will save you so much typing and improves readability. That same proposal has gone to the WinUI and WPF repos as well, hopefully they will follow soon.
Under the Hood
How was this implemented you ask? The change was implemented by Stephane, here. If we look at the code, we see that a TypeConverter has been used. Simply put what happens is you adorn a property with an attribute that tells the XAML engine to use a specific
TypeConverter. Then in the actual type converter you simply parse that value that is coming in, which will always be a string and convert that into something the property understands. And that will then be assi
To make that more concrete; in this case a string like
"1*, 2*, Auto, *, 300" comes in, the logic in the implemented type converter will split the string on the commas and the resulting values are converted into column or row definitions depending on which property we are looking at.
I hope you will enjoy this new functionality as much as I will! I know I will be removing loads of XAML from my apps. At the time of writing this has just been merged and is not available in NuGets yet.
If you really want to try it, check out the nightly packages of Forms. This is now available as of Xamarin.Forms 4.7-pre1.
Hero image based on: Paper vector created by freepik – www.freepik.com