Reputation: 3049
A technique I have used for a long time to do sorting in WPF is to create a CollectionViewSource and specifying SortDescriptions, eg
<Window.Resources>
<CollectionViewSource x:Key="testView">
<CollectionViewSource.SortDescriptions>
<cm:SortDescription PropertyName="FirstName" Direction="Descending"></cm:SortDescription>
<cm:SortDescription PropertyName="FamilyName"></cm:SortDescription>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
This has worked perfectly for everything I've thrown at it except with the DataGrid. It appears to work fine the first time through but if I change the data then the grid kills the sorting. It even kills it for other controls that use the same CollectionViewSource. I've created a sample project here
http://www.mikesdriveway.com/misc/GridSortIssue.zip
To test this issue run the project and click the Refresh Data button. Notice that the order of items changes. This only happens once, to test again stop and run the project again. Now delete the ItemsSource from the DataGrid and run the project again. This time when you click the Refresh Data button nothing happens, this means the sorting remains the same. Somehow the grid is killing the sorting in the CollectionViewSource. Is this a bug?
Cheers, Michael
Upvotes: 2
Views: 793
Reputation: 184346
That is rather odd, from what i can tell the SortDescription
of the underlying View
get cleared out when the source is changed, so if the SortDescriptions
of the CVS are not re-applied there is no sorting anymore.
One workaround would be to "reset" the SortDescriptions
:
var cvs = (CollectionViewSource)Resources["testView"];
var descriptions = cvs.SortDescriptions.ToArray();
cvs.SortDescriptions.Clear();
foreach (var descripton in descriptions) cvs.SortDescriptions.Add(descripton);
Upvotes: 2