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.

publicclassTypeExtension : MarkupExtension
{
privatestring _typeName;
publicstring TypeName
{
get { return _typeName; }
set
{
if (value == null)
thrownewArgumentNullException(“TypeName”);            _typeName = value;
}
}

publicoverrideobject ProvideValue(IServiceProvider serviceProvider)
{
// Get the IXamlTypeResolver from the service provider
IXamlTypeResolver xamlTypeResolver = serviceProvider.GetService(typeof(IXamlTypeResolver)) asIXamlTypeResolver;
if (xamlTypeResolver == null)
thrownewArgumentException(“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.

Brian Lagunas

View all posts

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.