【问题标题】:C# WPF DataGrid - DateTime formatting [duplicate]C# WPF DataGrid - 日期时间格式[重复]
【发布时间】:2018-03-21 19:20:03
【问题描述】:

我正在使用DataTable(在代码中创建),我使用DataGrid 显示它是DefaultViewDataTable 包含一个 DataColumn,它具有 DateTime,因为它是 DataType

DataGrid 将日期显示为:10/9/2017 12:00:00 AM。有没有办法在不将列的DataType 更改为string 的情况下将DateTime 值显示为10/9/2017

【问题讨论】:

    标签: c# wpf datetime datagrid format


    【解决方案1】:

    你的绑定应该是这样的

    {Binding Property, StringFormat=d}"
    

    完整示例

    <DataGridTextColumn Header="Your Header" Binding="{Binding Property, StringFormat=d}" ></DataGridTextColumn>
    

    【讨论】:

    • xaml 中的DataGrid 不包含列定义,它只是绑定到DataTable 的默认视图。完美运行,除了日期显示。
    • 让 c.给我一些时间
    【解决方案2】:

    您可以为DataGrid 处理AutoGeneratingColumn 事件:

    private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (e.PropertyType == typeof(DateTime))
        {
            e.Column = new DataGridTextColumn()
            {
                Binding = new Binding(e.PropertyName) { StringFormat = "d" }
            };
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      相关资源
      最近更新 更多