Archive for June, 2009

Show custom Date format in auto-generated DataGrid column

June 25, 2009

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

Enforce DataGrid to regenerate columns

June 17, 2009

It is simple:

DataGrid.AutoGenerateColumns =False
DataGrid.AutoGenerateColumns =True
 
And columns will be regenerated!