A review of markup extensions

XAML is simple, which is a good thing.  It is just an XML-based language used to declare objects and the relationships between them.  One side effect of being simple is that it can be verbose.  This cumbersome verbosity was one of the main reasons why the concept of markup extensions was introduced.  A markup extension can be used to turn many lines of XAML into one concise expression, as we will see later on.

Another side effect of XAML’s simplicity is that it does not have any “built in” knowledge of common artifacts used by WPF or the CLR; such as resource references, data binding, a null value, arrays, static members of a class, etc.  Since XAML can be an integral part of application development there needs to be some way for developers to express those ideas in it.  This is another major reason why markup extensions were added to Microsoft’s implementation of XAML.

Here is an example of several markup extensions put to use (in this demo, the StackPanel’s DataContext was set in the code-behind to a Person object):

Markup extensions put to use

All markup extensions derive from the abstract MarkupExtension class and override its ProvideValue method.  The naming convention is to append the word Extension to the subclass’s name (only the Binding class does not follow the pattern). The XAML parser allows markup extensions to be created within {curly braces} and it also allows you to omit the Extension suffix when using a markup extension, if you want to. 

In the XAML above, take a look at the TextBox’s Text property, and the CheckBox’s IsChecked property.  They both use the Binding markup extension to bind their values to a property on the data context (a Person object).  The Binding associated with the TextBox’s Text property is much less verbose than the IsChecked Binding.  The verbosity reduction would be even greater if the Binding configuration was more elaborate. 

If you want to see what this ugly demo app looks like, click on the thumbnail image here:
Markup extensions demo UI

Here are several useful resources regarding markup extensions:

Markup Extensions and XAML

Creating a Simple MarkupExtension

Limited generics support in Xaml

About these ads

One Response to A review of markup extensions

  1. [...] data binding capabilities. To use WPF data binding in a delayed fashion, I created a simple markup extension which creates a binding and manages the timer delay between [...]

Follow

Get every new post delivered to your Inbox.

Join 289 other followers

%d bloggers like this: