Sorting Data in a Real-Time WPF GridView

The GridView in the Windows Presentation Foundation (WPF) provides a very easy-to-use way of binding data to the display. Data that updates can implement the INotifyPropertyChanged interface to let WPF handle refreshing that data in the interface. By binding your data to a CollectionViewSource,  a software developer can even sort and filter the rows quickly and easily. So what’s the problem?

The sorting and filtering do not update when the property changed event fires. In order to get it to update, a software developer has to remove, then re-add the sort or filter. The performance on this is a large issue for a near real time software program. So, how does a software developer get around it? There are many ways to improve software performance, but since sorting was the key requirement for this software program, this can be done at the data layer. A software developer can create a collection that inherits ObservableCollection and overrides the Add and Remove functions. Both of these functions make sure to insert or remove data in a way that preserves the current sorting. Attaching an event to the property changed event of its contained items lets a software developer handle reordering when data changes. Then, we can use  delegate and multiple comparison functions to allow the data to be ordered ascending or descending on several different columns.

It may not be the most elegant solution, but it provides much better performance than a software developer can gain via the WPF alone. It is also very transparent and doesn’t mess with the data binding in any way. I use a binary search on the sorted column (reusing my compare delegate actually) to make sure that insertions are as quick as possible. Resorting the data when a column is changed is the slowest operation, but it’s OK that it is a bit expensive since it is ideally called less often. With a bit of effort, it can even be templated to allow more code reuse; I’ll be working on that later.