Things I Think Are Cool: Custom XAML Markup Extensions
Things I Think Are Cool is a blog series where I talk about things I have found interesting and helpful. They can be time savers, productivity tools, podcasts, books, products, or even people.
When I first started developing with Xamarin.Forms, I did everything within my power to stay away from XAML.
At first glance - XAML, with its striking similarity to HTML, struck me as wrong, as a toy language. I'm a real developer, creating real apps, not some watered down version running in a web view. Angle brackets are only for equality operators and lambdas ... that's it!
All C#. All the time.
I was young and foolish.
XAML is actually quite a powerful language. Not only does it let you build up your UI in an easy, expressive manner - it's super easy to read. It also lets you setup data bindings, access static variables on classes, grab info from resource dictionaries ... and these last couple of things are done through something known as XAML Markup Extensions.
You'll know you're looking at a markup extension when you see the familiar curly brace in the XAML code.
These markup extensions allow some code to be run in the background when setting a value to a property.
<Label
Text="{Binding Name}"
VerticalOptions="{StaticResource theVert}"
TextColor="{x:Static SomeClass.StaticColorProperty}"
/>
But you're not limited to the out of the box markup extensions, you can create custom ones, and that's what I want to talk about today in Things I Think Are Cool - Custom XAML Markup Extensions.
Why It's Cool
Generally speaking, when using XAML, properties of control's are set to a constant value.
It's through markup extensions that you can extend the XAML markup to make it run some code before setting a value to the property. (Like the whole data binding engine.)
You can create your own markup extensions by creating a class that implements the IMarkupExtension
interface.
It's cool then that you can then have that custom markup extension "intercept" and run some code, any code, before the value is set on the control's property.
You're not limited to setting control properties to static values or having to manipulate things to work through data binding and the like.
A classic example would be to load an embedded image (because there's no type converter from string
to ResourceImageSource
).
How To Get It
It's custom - so you need to code it yourself!
For documentation Chapter 10 in the Creating Mobile Apps with Xamarin.Forms covers it.
As for a tutorial, as I was writing this, I thought to myself that I needed to write a blog post on it ... so that will be coming shortly.