Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to format dates in dynamically built WPF DataGrid

We are binding an unknown result set to a WPF DataGrid at run time. Some of our columns are going to contain DateTime values and we need to properly format these date time fields. Without knowing which columns are going to be DateTime fields at design time, how are we able to format the columns at runtime?

We are using a DataTable's DefaultView to bind to the WPF DataGrid.

like image 960
FarrEver Avatar asked May 11 '09 15:05

FarrEver


2 Answers

Format the binding by StringFormat:

<DataGridTextColumn Header="Fecha Entrada"                      Width="110"                       Binding="{Binding EnterDate, StringFormat={}\{0:dd/MM/yyyy hh:mm\}}"                     IsReadOnly="True" /> 

I think it's better than writing code behind pieces of code

like image 157
Junior Mayhé Avatar answered Sep 21 '22 20:09

Junior Mayhé


I figured out how to do this in code...hopefully there is a way to mimic this in XAML. (Please post if you find a working XAML sample.)

To accomplish this in code, add an event handler for the Grid's AutoGeneratingColumn event, such as:

private void ResultsDataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) {     if (e.PropertyType == typeof(DateTime))     {         DataGridTextColumn dataGridTextColumn = e.Column as DataGridTextColumn;         if (dataGridTextColumn != null)         {             dataGridTextColumn.Binding.StringFormat = "{0:d}";         }     } } 
like image 21
FarrEver Avatar answered Sep 21 '22 20:09

FarrEver