If you have done any WPF application development I am sure you have used and fallen in love with the Static markup extension. If you’re are not familiar with it, the Static markup extension allows you to reference static fields and properties in your XAML markup.
For example; let’s assume we have a class with the following static field defined:
We can use this field in our WPF application as follows:
NOTE: “ext” is a namespace that has been defined to instruct the XAML parser where to find our static field.
Pretty cool right? Unfortunately if you are also doing any Silverlight development you will soon find that this wonderful and useful extension does NOT exist in Silverlight. Luckily for us in Silverlight 5 we were given the ability to write our own custom markup extensions. This can be done using either the IMarkupExtension or the abstract MarkupExtension class.
Now it’s time to create our own Static markup extension. I want to point out that there is a naming convention when creating custom markup extensions. The convention is as follows; ExtensionNameExtension. The name of the extension is followed by Extension. This is very similar to how you create attributes. You won’t actually be using the suffix when define them in XAML.
Let’s start by creating a new class called StaticExtension. The StaticExtension class should derive from the MarkupExtension abstract class. You will need to implement the abstract ProvideValue method. The code I used for the Static markup extension is as follows.
Now all I need to do is add a namespace to my Silverlight view and then use it in XAML as follows:
That’s it! I will definitely be using this quite often. I would like to mention that unlike in WPF where you don’t have to specify the “Member” property explicitly, in Silveright you have to explicitly set the Member property. This is because there is not a ConstructorArgument attribute in Silverlight. So until then you will need to have a little extra text in your markup syntax.