Type converter on Silverlight
Today we’ll talk a little bit about the role played by type converters in “transforming” XAML into C# objects. Here’s a quick example:
x:Name="bt" Click="bt_Click" Width="100"
Content="Say Hi" Background="Red" />
If you look carefully, you’ll see that Background expects a Brush object. All XAML attribute are strings by default. In other words, you’d need the following C# code to set the background of the button:
bt.Background = new SolidColorBrush(Colors.Yellow);
So, what’s going on here? Well, it’s simple: the parser uses a type converter to convert the string into the correct object. In practice, type converters are objects which inherit from TypeConverter class. You can associate a type converter to a type or to a property by using the TypeConverterAttribute. The parser will respect that option and will use the indicated type converter to translate the string into the expected object type.
Now, unlike WPF, where everything is really based on managed type converters, in Silverlight, there is an *unmanaged* type converter which is used for performing most of the common conversions you’d expect to happen (take a look at the internal SilverlightTypeConverter class and you’ll notice that you’ll end up using the “unmanaged” XcpImports type).
So, don’t expect to find many type converters by firing up .NET Reflector. Btw, you should keep in mind that you can still build and use your own type converters for your types. The XAML parser will always check the current property and/or type and if it’s associated with a managed type converter, it will honor that relationship and your converter will be used.
And I guess it’s all for now. Stay tuned for more on Silverlight.