WPF localization

To repro a bug I’ve created a simple WPF application that displays two labels bound to the same DateTime object. The bottom one is converted to a string using a IValueConverter. Both should be formatted the same but aren’t.
wpf_localization_1

By adding some trace lines to the Convert method I’ve discovered that the CultureInfo (en-US) parameter is different from the CurrentThread.CurrentCulture (nl-NL). I’ve configured my English Windows 8.1 with Dutch formatting for datetime.

On stackoverflow someone pointed me to IFormattable and the ToString overload that would accept the culture. My Convert method now looks like below.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture){
    System.Diagnostics.Trace.TraceInformation( "Convert Culture: {0}", culture.ToString());
    System.Diagnostics.Trace.TraceInformation( "Thread  Culture: {0}", System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
    System.Diagnostics.Trace.TraceInformation( "ThreadUICulture: {0}", System.Threading.Thread.CurrentThread.CurrentUICulture.ToString());
    var formattable = value as IFormattable;
    return formattable.ToString( null, culture);
}

Now the formatting looks alike, but not what I expected. The formatting should have been in Dutch (dd-MM-yyyy).
wpf_localization_2

By setting the Language property for the top framework element, the CultureInfo passed to the Convert method is changed. This has to be repeated on every Window. A very usefull tip from Rick shows how to do this in the OnStartup all at once.

protected override void OnStartup(StartupEventArgs e){
    base.OnStartup(e);
    FrameworkElement.LanguageProperty.OverrideMetadata( typeof( FrameworkElement),
        new FrameworkPropertyMetadata(XmlLanguage .GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
}

wpf_localization_3

Now the dates are printed the way you specify in the Control Panel > Region > Format. Remember to restart the Application (or Visual Studio when debugging) after you’ve changed the setting.

References

Stackoverflow answer to use IFormattable
WPF Bindings and CurrentCulture Formatting – Set Language App global

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.