I want to specify a default ordering at startup, but still allow the user to sort by clicking on the column headers. Sadly the SortDirection property is ignored when it is set - i.e. we get the correct column header arrow, but nothing is sorted.
Clicking on the headers manually, sorts the data correctly, so it's not the sorting itself. This is the simplified version I'm using:
<DataGrid ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=CurrentView}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Header 1" Binding="{Binding ApplicationName}"/>
<DataGridTextColumn Header="Header 2"
Binding="{Binding TotalTime}" SortDirection="Descending"/>
</DataGrid.Columns>
</DataGrid>
Update: I also tried adding SortDescriptions to the ICollectionView as proposed, without good results. Could this have something to do with the fact that I'm dynamically adding new items to the collection? I.e. at startup the list is empty and slowly filled and maybe the sortdescription is only applied once?
Take a look at this MSDN Blog
From above link:
DataGridColumn.SortDirection does not actually sort the column.
DataGridColumn.SortDirection is used to queue the visual arrow in the DataGridColumnHeader to point up, down, or to not show. To actually sort the columns other than clicking on the DataGridColumnHeader, you can set the DataGrid.Items.SortDescriptions programmatically.