WPF/C# - Applying date format to listview

Yatrix picture Yatrix · Aug 8, 2011 · Viewed 15.8k times · Source

I have a listview bound to a collection of objects. One of the properties is a DateTime object named startDate. It's displayed in the standard 1/1/2001 1:00:00 PM format

I want to put the date in yyyy-MM-dd HH:mm:ss.fff format just for display purposes. Is there a way to keep the underlying DateTime object in tact while displaying it in the desired format above? I'd prefer to do this in XAML as opposed to adding a display property to the object or something along those lines.

The objects implement the INotifyPropertyChanged interface, if that matters.

<ListView x:Name="lvBatches" 
                  SelectionMode="Single"
                  Margin="12,73,349,61" 
                  Background="WhiteSmoke" 
                  SelectionChanged="lvBatches_SelectionChanged"
                  ToolTip="Click on the column headers to sort by that column"
                  FontSize="10pt"
                  ItemContainerStyle="{StaticResource itemStyle}" 
                  ItemsSource="{Binding batchCollection}">
<!-- ... -->
    <GridViewColumn x:Name="colStart" 
                    Width="200" 
                    DisplayMemberBinding="{Binding startDate}">
        <GridViewColumnHeader Content="Start Date"
                              Click="GridViewColumnHeader_Click"/>
    </GridViewColumn>

Thanks in advance, all.

Answer

Ray picture Ray · Aug 8, 2011

Simple change the StringFormat in your binding.

DisplayMemberBinding="{Binding Path=startDate, StringFormat='yyyy-MM-dd HH:mm:ss.fff'}"