【问题标题】:DateTime format changing when used as DataGrid ItemSource用作 DataGrid ItemSsource 时 DateTime 格式发生变化
【发布时间】:2016-02-26 22:57:09
【问题描述】:

我有一个类,它有两个属性,一个字符串和日期时间。 DateTime 属性在构造函数中被赋值:

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

lastCheckIn 变量传递给构造函数的地方。

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

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

不太确定我哪里出错了,任何帮助将不胜感激!

【问题讨论】:

  • DateTime 没有格式。格式是DateTime 转换为string 时的格式。基本上,您需要告诉您的DataGrid 在查看时您希望DateTime 的格式。 stackoverflow.com/questions/7978249/…

标签: c# wpf datetime datagrid


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多