Share via


{x:Type} and {x:Static} in Silverlight

The question:

Silverlight does not support {x:Type} and {x:Static} xaml markups so far in V3.  They has been important building blocks in WPF applications.  How can we get the benefit from them in Silverlight application as well?

{x:Type} in xaml is to provide a Type value to a property, such as this in WPF
image

In Silverlight, it works simpler in some way. For build in Type properties, such as Style.TargetType and ControlTemplate.TargetType, you can use:image

However, in Silverlight, if you define your own custom dependency property and want to use similar syntax to define the type in xaml, no luck.  Silverlight xaml parser cannot recognize “local:MyListBox” as a Type.  You can only get it as a string.  And Silverlight does not support xaml markup extension yet, so you cannot define your own {GetType} either.

How can we assign a Type property in silverlight xaml?

First thought (not a solution)

How about using a static TypeProvider like this?image
andimage
Unfortunately, {x:Static} is not supported in silverlight xaml either.

Solution one

Solutions one is to use static resource instead of the static class.  It’s like a singleton (not a strict singleton though) to use a reference to an instance instead of static property.  Suppose to change TypeProvider into a non-static classimage
and define the instance in app.xaml image
Then you can reference the type in your xaml as this:
image  It requires the custom property “BuddyType” to be a dependency property to support binding, and binding has its runtime overhead.  But it works just like {x:Type}, or just like {x:Static} if you look at it in a different perspective.

Solution Two:

As you might complaint, it looks clumsy.  Depending on how are you going to use the Type, there might be more elegant way to solve this issue.

Suppose the type is serving as a factory pattern, where we are creating the instance of given type whenever a new type is assigned to the property.  e.g.
image
We might find providing the Type through Binding is a detour to our task.  We can use Prototype Pattern to serve the same purpose with much more elegant code.

First, we need IBuddy to be an ICloneable as this
image
and implement it on every concrete type you want to create 
image
So you can define your prototype instance in App.xaml
image
Now, you can reference the prototype in your xaml code as image
Because the factory is now using a prototype patter as this: image   
Although the last solution appears to have more sample code in this blog post, it actually the most maintainable code because most code are within base class and constructions, the usage is very simple and fast.  It also support plain property without going through the overhead of DP.

Conclusion

{x:Type} and {x:Static} are important xaml markup extensions, and we wish Silverlight will pick them up in the future release.  However, until then, we have to live with the workarounds as above.