在 C# WPF 中,如果要设定
DataGrid
控件中日期时间列的显示格式,可以通过以下代码实现:
DataGridTextColumn
对象并设置
Binding
属性。
<DataGridTextColumn Header="Date" Binding="{Binding Date, StringFormat=\{0:yyyy-MM-dd\}}" />
上述代码中,Binding 属性绑定了 Date 字段,并使用了格式化字符串 {0:yyyy-MM-dd} 将日期时间格式化为年月日的格式。
在代码中通过 DataGridTemplateColumn 对象自定义单元格内容。
<DataGridTemplateColumn Header="Date">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Date, StringFormat=\{0:yyyy-MM-dd\}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
上述代码中,在 DataGridTemplateColumn 的单元格模板中使用了 TextBlock 控件显示日期时间,并使用了格式化字符串 StringFormat=\{0:yyyy-MM-dd\} 将其格式化为年月日的格式。
以上是设置 DataGrid 控件中日期时间列显示格式的两种方法。根据需求,可以选择使用其中一种或两种方式都使用。