Ladislav Louka
Ladislav Louka

Reputation: 286

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.

Upvotes: 1

Views: 2185

Answers (2)

PeteH
PeteH

Reputation: 2454

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).

Upvotes: 0

Ladislav Louka
Ladislav Louka

Reputation: 286

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

Upvotes: 2

Related Questions