A Silverlight x:Type Markup Extension

Brian Lagunas / Wednesday, January 30, 2013

A while back I wrote a x:Static markup extension for Silverlight that mimicked WPF’s x:Static functionality.  Well, today I had an email from a reader asking if I could provide the code for a Silverlight version of the WPF x:Type markup extension.  If you read the post for the Silverlight x:Static markup extension, you probably noticed how involved that task really was.  So you would expect a Silverlight version of the x:Type to be the same.  Well, it’s not.  The implementation is actually extremely simple.

public class TypeExtension : MarkupExtension
{
    private string _typeName;
    public string TypeName
    {
        get { return _typeName; }
        set
        {
            if (value == null)
                throw new ArgumentNullException("TypeName");

            _typeName = value;
        }
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        // Get the IXamlTypeResolver from the service provider
        IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
        if (xamlTypeResolver == null)
            throw new ArgumentException("xamlTypeResolver");

        // Use the type resolver to get a Type instance
        Type resolvedType = xamlTypeResolver.Resolve(TypeName);

        return resolvedType;
    }
}

Wow that was freaking easy!  Make sure you add your namespace to your view and use the extension as follows:

<controls:EditorDefinition TargetType="{controls:Type TypeName=sys:String}">

“Controls:” is the namespace that my control and extension exists in, and the “sys:” namespace points to System in mscorlib.  Now remember, unlike in WPF where you don’t have to specify the “TypeName” property explicitly, in Silverlight you have to explicitly set the TypeName 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.