Tuesday, June 14, 2011

Silverlight 5 MarkupExtensions –Localization just got a whole lot easier

One of the features we’ve been most waiting for in Silverlight is the support for Markup Extensions, which WPF had since day one. 
In order to support localization, we can create a markup extension like so:

public class TranslationExtension : IMarkupExtension<string>
{
public string Key { get; set; }
public TranslationExtension()
{
Key = String.Empty;
}
public override string ToString()
{
return ProvideValue(null);
}
// for design time only. runtime is set in app.xaml.cs
public static CultureInfo Culture = new CultureInfo("en");
public string ProvideValue(IServiceProvider serviceProvider)
{
String s = Translations.ResourceManager.GetString(Key, Culture);
if (String.IsNullOrEmpty(s))
{
Debug.WriteLine(Key + " not found in RESX file!");
return "!" + Key + "!";
}
return s;
}
}

Read more: Lego for grownups