0
votes

I'm using a DatePicker to display a DateOfBirth property for a given class:

<DatePicker Text="{Binding SelectedPerson.DateOfBirth }" />

I can see from the underlying class (SelectedPerson) that the Date is correct (i.e. day, month & year are correct), yet in the DatePicker the day and the month are reversed.

Thus, 1st February 2016, is displayed as 2nd January 2016 on the DatePicker.

What am I doing wrong? Thanks in advance.

3
DateOfBirth is a DateTIme? Locale settings can affect format. Looks like NA\EU confusion in your case.icebat

3 Answers

1
votes

I was simple binding to the wrong element. Should have been SelectedDate, not Text:

<DatePicker SelectedDate="{Binding SelectedPerson.DateOfBirth}" />
0
votes

In WPF, any bindings which don't explicitly specify a culture will use the invariant culture instead. That means you'll get American date and number formats, ignoring your current regional settings.

This is a long-standing problem, which the WPF team considers to be "by design".

The standard workaround is to override the property metadata for the FrameworkElement's Language property:

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

This needs to be done before you show any UI - usually in the OnStartup event.

Unfortunately, this will only solve the problem for elements derived from FrameworkElement. The Run element, for example, derives from FrameworkContentElement, and so it won't be affected by this change. And you can't override the metadata for the FrameworkContentElement, as it has already been overridden.

Another alternative is to create and use a custom binding which always initializes the culture to CultureInfo.CurrentCulture:

public class CultureBinding : System.Windows.Data.Binding
{
    public CultureBinding(string path) : base(path)
    {
        ConverterCulture = CultureInfo.CurrentCulture;
    }

    public CultureBinding()
    {
        ConverterCulture = CultureInfo.CurrentCulture;
    }
}
-1
votes

I don't know what you'r doing wrong, but as a workaround, you should try the Date.ToString() method (docs for this here) and if your SelectedPerson.DateOfBirth is a DateTime object (if it's not, you should consider do that, just saying :p)

EDIT: Another thing you should consider is to set the correct culture see here