用作DataGrid ItemSource时DateTime格式更改

时间:2015-11-24 13:15:25

标签: c# wpf datetime datagrid

我有一个有两个属性的类,一个字符串和一个DateTime。 DateTime属性在构造函数中分配了一个值:

this._lastCheckIn = DateTime.Parse(lastCheckIn.ToString("dd/MM/yyyy HH:mm"));

将lastCheckIn变量传递给构造函数。

我可以在运行时看到该对象是使用我在此处指定的格式使用DateTime创建的,但是当它在DataGrid上显示时,格式将恢复为US。

以前我的对象中有一个字符串而不是DateTime,它显示格式正确但在数据网格中按升序或降序排序时没有正确排序。 2015年1月25日将显示高于2015年2月24日。

不太确定我在哪里出错了,任何帮助都会非常感激!

2 个答案:

答案 0 :(得分:2)

您可以在列绑定中选择字符串格式

<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding MyDate, StringFormat=\{0:dd.MM.yy \}}" />
    </DataGrid.Columns>
</DataGrid>

答案 1 :(得分:0)

使用运行应用程序的系统文化显示日期。您可以更改数据网格本身的日期时间格式,也可以在启动时将其应用于整个应用程序。

var culture = Thread.CurrentThread.CurrentCulture;
culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy HH:mm";

var uiCulture = Thread.CurrentThread.CurrentUICulture;
uiCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy HH:mm";
相关问题