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.
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
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}"; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With