简体   繁体   中英

Datetime format programmatically WPF Datagrid

I have a DataGrid in a window of WPF, it can have different columns (which are chosen programmatically). Often many of them are Dates, but they are by default formatted as mm/dd/yyyy hh:mm:ss tt. I however need all those fields shown as dd/mm/yyyy. I could find how to do it in xaml defined columns, but all my columns are programmatical, so I need to do it either in c# or define in XAML all datetime columns to be formatted this way.

Found the ability to make all DateTime columns formatted by handling the AutoGeneratingColumn of the DataGrid and adding binding whenever the type is DateTime

if (e.PropertyType == Type.GetType("System.DateTime")) {
    DataGridTextColumn col = e.Column as DataGridTextColumn;
    col.Binding = new Binding(e.PropertyName) { StringFormat = "dd/MM/yyyy" };
}

Found the solution here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/f32a6639-60c8-47c7-9ae0-dceb221fd9cf/string-format-for-the-datagrid-column?forum=wpf

Write a converter, as explained in one of the answers to WPF datagrid date column with system custom short date format .

By passing execution to code rather than xaml you have full control over the string that is outputted. I use mine to show mixture of long date and short time (which confused the heck out of the xaml parser).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM