Harald Harald - 1 year ago 95
C# Question

Date formatting in WPF datagrid

I already searched stackoverflow for a solution and found this:

Need to format dates in dynamically built WPF DataGrid

My problem is, that I load some data out of my SQL-Server-Database and want to show them in my WPF-application in a DataGrid. This works very well.
The only thing I want to change is that the date column is in the format "DD/MM/YYYY HH:MM:SS" and I want to have "DD.MM.YYYY".
Ok, then I looked at the link below and tried this in my programm:

<Grid Width="648" Height="263">

<ColumnDefinition Width="172*" />
<ColumnDefinition Width="90*" />
<ColumnDefinition Width="386*" />

<DataGrid Name="dgBuchung" Height="213" HorizontalAlignment="Left" Margin="30,16,0,0" VerticalAlignment="Top" Width="595" AutoGenerateColumns="True" ItemsSource="{Binding}" Grid.ColumnSpan="3" Foreground="Black" BorderBrush="#FF688CAF" Opacity="1" Background="White" BorderThickness="1" >
<!-- <ab:DataGridTextColumn Header="Fecha Entrada" Width="110"
Binding="{Binding date, StringFormat={}{0:dd/MM/yyyy}}" IsReadOnly="True" />


The out commented part is my way of solution but it throws a XMLParseException.
First of all, is this way of solution possible while using AutoGenerateColumns?
If no, how else can I try to handle this?
If yes, what is the problem with the code above?

My question isn´t solved because I decided not to rebuild my application, isn´t there a solution with AutoGenerateColumns=true?

Answer Source

Don`t forget to use DataGrid.Columns, all columns must be inside that collection. In my project I format date a little bit differently:

        <tk:DataGridTextColumn Binding="{Binding StartDate, StringFormat=\{0:dd.MM.yy HH:mm:ss\}}" />

With AutoGenerateColumns you won`t be able to contol formatting as DataGird will add its own columns.