具有系统自定义短日期格式的WPF datagrid日期列
这与使用WPF数据网格的自定义日期格式线程略有不同。
This is slightly different wrinkle to the custom date format threads with WPF datagrids.
我的Win7框有一个自定义的短日期字符串,在控制面板中定义为dd-MM-yy。我希望DataGrid中的日期列使用该设置进行显示。视图模型具有一个称为日期的DateTime。
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'.
我尝试了此操作
<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>
日期列显示为m / d / yyyy。无论是否自定义,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的工作方式似乎有所不同。即使没有StringFormat,也可以使用自定义的短日期格式(并且直接绑定到视图模型中的DateTime)。
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).
我可以通过以下方法在DataGrid中解决此问题:在视图模型(日期-> DateFormatted)中创建一个字符串属性,在该模型中,getter使用DateTime.ToShortDateString,但是我不确定这是执行此操作的最佳方法。而且我还没有计算出绑定的TwoWay部分...:P
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
创建一个转换器并在在datetime列绑定。继承IValueConverter的类。接收DateTime并返回一个字符串。
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.