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... :P
I think the solution is rather simple. The
StringFormat
you're using is invalid so it gets ignored andDataGridTextColumn
resorts to default format. If you instead specifydd
asStringFormat
, it works as you expect.so your final binding will look like this (including TwoWay):
However, please note that this is going to be confusing in edit mode as even though column is showing you just a number (the day) it will actually expect you to write in a valid date before it accepts that input and formats it again as you request it to. You can work around this by using a
DataGridTemplateColumn
instead and specifyingCellTemplate
andCellEditingTemplate
in there.You have to set the
UICulture
when your application starts to what it should be. Then it will use the right formatting from the computer. The XAML resources always default toen-US
you see.Try setting/binding this as your
Converter
:Then set up your XAML like this:
Create a converter and use it in the binding at the datetime column. A class that inherits IValueConverter. Receives a DateTime and returns a String.
This allows you to configure the date time format.
VB Code
C# Code
XAML Code