Tuesday, April 26, 2011

Silverlight 5.0: Custom Markup Extensions and Roles

Starting from Silverlight 5.0 you can create custom Markup Extensions and this is an interesting feature to easily encapsulate some logic and make it easy to be applied to properties in the XAML markup. Until now you could only use a few extensions to apply resources (StaticResource), make databinding (Binding) and connect properties with parts of a template (TemplateBinding) but now, implementing a really simple interface you can build your own.

public interface IMarkupExtension<out T> where T: class
{
T ProvideValue(IServiceProvider serviceProvider);
}

Using this interface you can specify the type to which the markup extension can be applied (the generic type T) but if you do not need a control about this type you can extend the MarkupExtension abstract class that is like you are extending IMarkupExtension<object>.
Inside the ProvideValue method there is the whole logic of the extension and using the IServiceProvider passed by the runtime you can get access to three services that let you get some informations about the markup where the extension is located.

IRootObjectProvider: provide a reference to the Root object of the VisualTree which the element is part of
IXamlTypeResolver : is able to resolve the name of the tags in the markup to the corresponding type.
IProvideValueTarget : gets a reference to the property and the elements which the markup extension is assigned
To retrieve an instance of this services you can use the GetService method on the IServiceProvider instance.

IProvideValueTarget target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));