WPF IValueConverter Culture isn’t what you expect

I came across a defect that our DateTime IValueConverter wasn’t showing the local users regional settings.

I set a breakpoint into the converter and looked at the culture variable being passed in. The ShortDateFormat was "M/d/yyyy".

Well, my regional was set to "dd-MMMM-yy"

What gives?

I checked CultureInfo.CurrentUICulture. It had the right format string.

I attempted the language override fix:

[csharp]
  //Defaulting WPF to use at least the current cultures default values. Converters will still not use the local UI culture by default...
                FrameworkElement.LanguageProperty.OverrideMetadata(
                        typeof(FrameworkElement),
                        new FrameworkPropertyMetadata(
                        System.Windows.Markup.XmlLanguage.GetLanguage(CultureInfo.CurrentUICulture.IetfLanguageTag)));
[/csharp]

Didn’t help with my scenario at all.

So, in the end, I just used CultureInfo.CurrentUICulture to format the string. A bit annoying.

[csharp]
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null) return NoDateString;
            var d = value as DateTime?;

            if (d.HasValue) return d.Value.ToString(parameter.ToString(),System.Globalization.CultureInfo.CurrentUICulture);
            return value.ToString();
        }
[/csharp]

If you find a better way, please feel to drop me a note.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *