Best Practices: Localize a WPF application (Part 2)

Coordinator
May 7, 2009 at 7:31 PM
Part 1 discusses how to localize resources for WPF applications. In this part I would like to talk about culture aware parsing and formatting with the WPF binding infrastructure.
 
The .NET Framework provides functionality which respects the “Regional and Language Options” of Windows for parsing, formatting and sorting of user data (e.g. string.Format). These regional settings are represented in .NET by the CurrentCulture property.
 
By example the methods
 
    Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
    Console.WriteLine(string.Format("{0:d}", DateTime.Now));
 
return “07.05.2009”. This is the German short date format.
 
The data binding of WPF doesn’t respect the CurrentCulture settings. Instead the binding uses the FrameworkElement.Language property which has the default value “en-US”. Therefore, all bound properties are formatted in the “en-US” culture regardless of the operating system settings.

You have to write user code so that data bound properties are formatted in the correct culture. Add the following lines into the App class:

    static App()
    {
        FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(
            XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
    }

These lines overwrite the default value of the language property with the current culture setting of .NET.

 
Download Code: http://compositeextensions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27102