WPF datagrid date column with system custom short date format

datetimewpfwpfdatagrid

This is slightly different wrinkle to the custom date format threads with WPF datagrids.

My Win7 box has a custom short date string defined in the Control Panel as dd-MM-yy. I want a date column in a DataGrid to use that setting for display. The view model has a DateTime called 'Date'.

I tried this:

   <DataGrid AutoGenerateColumns="False" Name="dataCondition" ItemsSource="{Binding}">
    <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Name}" ></DataGridTextColumn>
      <DataGridTextColumn Binding="{Binding Date, StringFormat=d}" />
      <DataGridTextColumn Binding="{Binding Comment}"></DataGridTextColumn>
    </DataGrid.Columns>
  </DataGrid>

The date column shows up as m/d/yyyy. Doesn't the DataGrid use the system short date setting, irregardless if it's custom or not?

WPF DatePickers seem to work differently. The custom short date format is used even without a StringFormat (and being bound directly to a DateTime in the view model).

I can get around this problem in the DataGrid by creating a string property in the view model (Date -> DateFormatted) where the getter uses DateTime.ToShortDateString, but I'm not sure this is the best way to do this. And I haven't worked out the binding TwoWay part yet… 😛

Best Answer

Try setting/binding this as your Converter:

[ValueConversion(typeof(DateTime), typeof(String))]
public class DateConverter : IValueConverter
{
    private const string _format = "dd-MM-yy";

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime date = (DateTime)value;

        return date.ToString(_format);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DateTime.ParseExact((string) value, _format, culture);
    }

}

Then set up your XAML like this:

<Window.Resources>
    <wpfDataGridMisc:DateConverter x:Key="dateConverter"/>
</Window.Resources>

<DataGridTextColumn Binding="{Binding Date, Converter={StaticResource dateConverter}}"/>
Related Topic