2

I'm binding a standard DatePicker to a property in my codebehind like so:

XAML:

<DatePicker Text="{Binding Start, Mode=TwoWay}" Width="150" BorderBrush="LightGray" VerticalAlignment="Center" Margin="3"/>

Code:

public DateTime Start
{
    get { return _start; }
    set
    {
        _start = value;
        RaisePropertyChangedEvent("Start");
    }
}

In the constructor I initialize the value to DateTime.Now, which today is January 8th. 2014 (that should unambigous across different languages). However I'm on a danish machine so the string formatted value will be 8/1/2014 as opposed to the US style 1/8/2014.

The first problem is that the date picker shows the value formatted as US style, and when I open the drop down, it also says August 1st.

The second problem is worse though. When I select e.g. December 1st from the drop down, the text says 12/1/2014, which is correct in US style, but the actual datetime selected (on the property) is the 12th of January, which matces the Danish style...

I'm guessing it's because of some issue in converting to/from localized string representations of a DateTime, but why is the date picker ignoring localization? And how can I fix it?

sondergard
  • 3,184
  • 1
  • 16
  • 25

3 Answers3

1

D'oh ... I was binding to the Text property rather than the SelectedDate property.

sondergard
  • 3,184
  • 1
  • 16
  • 25
1

Why not just attach to SelectedDate and you can also control the DateFormat

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
0

For some reason, when you bind your DateTime property to the Text of a DatePicker in XAML, the date value that gets sent to your property setter will be in the EN-US culture regardless of what your desired culture actually is.

To fix this you need to add the following in your application startup.

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

This could be in Application_Startup() of App.xaml.cs, or in Main if you're loading your WPF in a class library.

See here - StringFormat Localization issues in wpf

Richard Moore
  • 1,133
  • 17
  • 25