This is a mirror of official site:

Using Custom Markup Extensions in Silverlight 5

| Sunday, August 5, 2012
The first beta of Silverlight 5 was announced at MIX this week and is available for downloading. As such, I’ll be blogging about the new features in weeks to come. I’ll also be delivering sessions on Silverlight 5 at several upcoming conferences, including Microsoft TechDays in Belgium, Microsoft DevDays in the Netherlands, Devscovery in Redmond, WA, and Microsoft TechEd in Atlanta. If you plan to attend any of those conferences, I’d love to see you in my sessions!

One of the most exciting features that Silverlight 5 introduces – and one that has been a long time in coming to the platform – is custom markup extensions. My fellow coconspirator and Silverlight MVP Jeremy Likness presented a custom markup extension that uses MEF to satisfy imports on object instances declared in XAML. I’d like to present a custom markup extension of my own – one that retrieves RESX localization resources and simplifies the task of adding localization support to Silverlight applications.

In the past, RESX-based localization was usually performed in Silverlight XAML with the help of the built-in {Binding} markup extension. To demonstrate, the following example declares an instance of the ResourceManager wrapper class named Resources (which is generated by Visual Studio from Resources.resx), assigns the Resources instance to the DataContext property of a TextBlock, and uses a data-binding expression to set the TextBlock’s Text property equal to the Greeting property of the Resources instance:

    <local:Resources x:Key="Localize" />
  <TextBlock Text="{Binding Greeting}" DataContext="{StaticResource Localize}" />
It works, but it makes you wonder why you have to resort to data binding to make localization work when localization is such a common task in Silverlight applications.

You can make this work a little more cleanly by writing a custom markup extension. Such an extension might be applied this way:

    Text="{local:Resx ResxKey=Greeting, ResxType=Resources, Default=Welcome}" />
In this example, Resx is the custom markup extension, ResxKey identifies the localization resource to be loaded, ResxType identifies the ResourceManager wrapper class that provides access to that resource, and Default is an optional default value that’s used if the specified localization resource doesn’t exist or can’t be retrieved. Better, is it not? And it’s just one of a million different applications for custom markup extensions.

QR: Inline image 1

Posted via email from Jasper-net