Need to format dates in dynamically built WPF DataGrid

FarrEver picture FarrEver · May 11, 2009 · Viewed 51.8k times · Source

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.

Answer

Junior Mayhé picture Junior Mayhé · Aug 21, 2009

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