Skip to content

ObservableListView: Provide change notifications for sorting and filtering

jbe2277 edited this page Mar 11, 2024 · 9 revisions

.NET comes with the ObservableCollection<T> class. It is often used when a list of data should be shown within the UI. It provides notifications when items get added, removed, or when the whole list is refreshed. Components like the WPF ListBox react on these notifications and update the UI accordingly.

Note: The ObservableCollection implements the INotifyCollectionChanged interface. Every other collection that implements the same interface would work as well.

In UI design a list of elements is often combined with sorting and filtering. When the data collection does not change as long the UI is shown then this can be accomplished with simple LINQ expressions.

// The resulting collection is not observable anymore. 
// By using LINQ the change notifications get lost.
var result = observableCollection.Where(x => x.Name == filter).OrderBy(x => x.Name);

But more often the underlying data collection can be modified (e.g. Delete item button) while some sorting or filter is active. The ObservableCollection<T> does not support sorting and filtering out of the box. A solution is using the CollectionView. It is a layer on top of the data collection which provides sorting and filtering capabilities without manipulating the original collection. The drawback of the CollectionView is that it can only be used by WPF applications. And the usage is cumbersome.

The Win Application Framework (WAF) provides the ObservableListViewCore<T>. This class works like the WPF CollectionView but it has no dependency to any UI Framework.

ObservableListViewCore

  • Represents an observable list view for filtering and sorting a data collection.
  • Does not manipulate the source collection.
  • Multiple observable list views can be used with the same data collection.
  • When the source collection notifies a change via the INotifyCollectionChanged interface (like ObservableCollection<T>) then this list view updates automatically.
  • Use the Update method to manually update the list view.
  • Filter and Sort can be defined by LINQ expressions.
  • The list view implements the INotifyCollectionChanged interface to update its consumers about changes.
  • No dependency to any UI Framework. So, it can be used with MAUI, WinUI, WPF and any other consumer.
  • Consider calling Dispose when the list view is not needed anymore so that the CollectionChanged event at the source collection gets unregistered.

Sample

var listView = new ObservableListViewCore<Person>(personList, null, 
        x => x.Name == filter, x => x.OrderBy(y => y.Name));

See also: This class is used by the reference sample applications BookLibrary and InformationManager.

Clone this wiki locally