Show custom Date format in auto-generated DataGrid column

The problem in WPF DataGrid is: data is always shown in US long format. Probably due to some bug in WPFToolkit. But we don’t want to change WPFToolkit. We try to avoid the issue.

Really useful link is:
http://stackoverflow.com/questions/848702/need-to-format-dates-in-dynamically-built-wpf-datagrid

The solution of Bryan Anderson:

<wpfToolkit:DataGrid>
   
<wpfToolkit:DataGrid.Resources>
       
<DataTemplate DataType="{x:Type DateTime}">
               
<TextBlock Text="{Binding StringFormat={0:d}}"  />
       
</DataTemplate>
   
</wpfToolkit:DataGrid.Resources>
    ...
</wpfToolkit:DataGrid> 

Doesn’t work by me ;-( ,

but the solution of FarrEver with AutoGeneratingColumn() event is a good idea.

But: it is still the US long! WPFToolikt doesn’t use computer’s short date format!

What we can do? We can hard code the format, but use the computer’s regional settings. Then your customers see the date format they used to see. Code:

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 + “}”

        End If
    End If
End Sub
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: