DateTime Not showing with currentculture format in

2019-03-24 15:51发布

问题:

In WPF I am trying to Bind a date property in a DataGrid and I can only sort if it's bound to a DateTime property.

The application should show the date in a format corresponding to the user's Region and Language settings.

The issue is that when the date is a string property, it shows according to the Region settings, but when the property is bound to a DateTime the date format defaults to American rather than the correct region.

So if it's bound to a string property the sorting by column doesn't work, and if it's bound to a DateTime property, it doesn't convert to the correct region.

回答1:

That's because the binding system uses the culture defined by the FrameworkElement.Language property, which doesn't automatically match the current culture (which is a bit silly IMO, but that's the way it is...).

Fortunately there's an easy way around it, you just need to override the metadata for the Language property in your application static constructor, as shown here:

public partial class App : Application
{
    static App()
    {
        FrameworkElement.LanguageProperty.OverrideMetadata(
            typeof(FrameworkElement),
            new FrameworkPropertyMetadata(
                XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
    }
}


回答2:

The Localization sample of the WPF Application Framework (WAF) shows how to solve your issue.