I have a simple collection that gets updated in real-time. The data is displayed in a DataGrid in WPF. When a user sorts the DataGrid and the data changes the grid is updated with the new data but does not resort the data.
Anyone find a good way to resort the data when the underlying collection changes? I can easily determine when a collection change occured but so far I haven’t had much success in resorting.
Found I can do this:
SortDescription description = grdData.Items.SortDescriptions[0];
grdData.ItemsSource = null;
grdData.ItemsSource = Data;
grdData.Items.SortDescriptions.Add(description);
if(description.PropertyName=="Value")
{
grdData.Columns[1].SortDirection = description.Direction;
}
else
{
grdData.Columns[0].SortDirection = description.Direction;
}
But it’s quite the hack. Anything come up with something better?
This is a bit tricky and largely depends on the underlying data source, but here’s what I do:
First, and foremost, you need a data type that is sortable. For this, I’ve created a “SortableObservableCollection” since my underlying data type is an ObservableCollection:
Now, with that as the data source, I can detect sorts on my DataGrid and resort the actual data. To do this, I’ve added the following event handler to my DataGrid’s Items’ CollectionChanged event:
One of the reasons this works a little better than using the SortDirection is in the instance of doing combined sorted (hold shift down when doing sorts on your columns and you’ll see what I mean).