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
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}";
}
}
}
<DataGridTextColumn Header="Last update"
Width="110"
IsReadOnly="True"
Binding="{Binding Path=Contact.TimeUpdate, StringFormat={}\{0:dd/MM/yyyy hh:mm\}, Mode=OneWay}" />
i run this way. its work complete .
<TextBlock Text="{Binding Date_start, StringFormat=\{0:dd-MM-yyyy\}, Mode=OneWay}" />
Hey you can set the locale culture info in the constructor of the WPF form as
this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);
Or you can include the xml markup xml:lang="en-GB" in the window header markup
The answer of FarrEver, May 11 is good, but by me it doens't function. i still get American mm/dd/yyy instead my German dd/mm/yyyy. So I propose to find the regional settings of computer and use it in StringFormat
Private Sub DGrid_AutoGeneratingColumn(ByVal sender As System.Object, ByVal e As Microsoft.Windows.Controls.DataGridAutoGeneratingColumnEventArgs)
If e.PropertyType Is GetType(DateTime) Then
Dim dataGridTextColumn As DataGridTextColumn = TryCast(e.Column, DataGridTextColumn)
If dataGridTextColumn IsNot Nothing Then
Dim ShortDatePattern As String = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern
dataGridTextColumn.Binding.StringFormat = "{0:" + ShortDatePattern + "}" '"{0:dd/MM/yyyy}"
End If
End If
End Sub
see also: my blog
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