0

Here is a binding expression I have

<TextBlock Text={Binding MyDateProp, StringFormat=d} />

My machine default culture is en-GB. In App.xaml.cs I override OnStartup method like below

protected override void OnStartup(StartupEventArgs e)
{
        var newCulture = new CultureInfo("ru-RU", true);
        newCulture.DateTimeFormat.ShortDatePattern = "dd MMM yyyy";
        Thread.CurrentThread.CurrentCulture = newCulture;
        base.OnStartup(e);
}

I would like text to look like 01 Янв 2001 but it still shows me 1/1/2001. What culture does binding use and how can I force it to use the culture I want?

Demarsch
  • 1,419
  • 19
  • 39

2 Answers2

2

I had the same problem some time ago with WPF controls ignoring culture. Did you already try changing the following:

FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
    XmlLanguage.GetLanguage(CultureInfo.CurrentUICulture.IetfLanguageTag)));

Here is a question that talks about it further

Also you have StringFormat of d which is the default short date format. Looks like Windows defaults to dd.MM.yyyy for ru-RU short date. For this you have two options.

Change the shortdate format for you whole application by specifying the shortdateformat onstartup like your doing.

 newCulture.DateTimeFormat.ShortDatePattern = "dd MMM yyyy";

Or changing the date format also on each control for example:

<TextBlock Text={Binding MyDateProp, StringFormat={}{0:dd MMM yyyy} />

In your binding. If you specify stringformat you will have to do this on every control you want that date format. So it depends on what your application needs are.

Community
  • 1
  • 1
kmcnamee
  • 5,097
  • 2
  • 25
  • 36
  • Now I did it but looks like it is now using pure 'ru-RU' CultureInfo without my fix for ShortDatePattern – Demarsch Mar 16 '15 at 00:14
  • you have d as the stringformat specifier which will show up as the default short date format now that the control is picking up the Russian culture. D is the long date format. – kmcnamee Mar 16 '15 at 00:26
  • yes, I will use it that way. However I wonder if I can set up ShortDateFormat on a CultureInfo level so I don't need to specify exact format every time – Demarsch Mar 16 '15 at 10:22
  • yes specifying shortdatepattern at culturelevel will be a one and done type thing. It depends on if you need this short date in all your controls in your application or just one... – kmcnamee Mar 16 '15 at 10:48
1

Since Text property is of type DateTime, textBlock will internally call ToString() on binded property. So, what you have to do is to set ConverterCulture property of binding.

<TextBlock xmlns:g="clr-namespace:System.Globalization;assembly=mscorlib"
           Text="{Binding MyDateProp, StringFormat=d,
                          ConverterCulture={x:Static g:CultureInfo.CurrentCulture}}"/>
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185