Type converter on Silverlight

Published Wed, Nov 18 2009 11:09

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:

<Button xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 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.

Filed under: ,

Comments

# LA.NET [EN] said on Monday, November 23, 2009 6:26 AM

Markup extensions allows you to extend the expressibility of XAML. You use markup extensions to escape

# ASPInsiders said on Monday, November 23, 2009 6:44 AM

Markup extensions allows you to extend the expressibility of XAML. You use markup extensions to escape

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover