Skip to content
Tags

Data binding to an ObservableCollection which is updated from another thread in WPF

by mstrid on March 7th, 2012

The problem

The ObservableCollection class in C# is not automatically supporting updating the view/GUI via data binding if it is updated from another thread. This differs from how data binding is handled when binding to an instance implementing the INotifyPropertyChanged interface, where this is handled automatically.

If you attempt this by data binding the ItemSource proprety of a ListBox you get a NotSupportedException with the following exception message:

This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.

It looks like this when debugging in Visual Studio:

SNAGHTML3f8009

See the attached source code for the complete sample, sorry for the naïve implementation with a mix of data binding, code behind and implementation in the constructor but I think the basic idea is pretty simple to understand. Smile

 

The solution

Credits where credits are due, this solution is inspired by this blog post.

The best solution I have found so far is to extend the ObservableCollection a bit to make it handle the dispatching to the right thread. It expects that the collection is created from the GUI thread so that it can save a reference to the dispatcher.

The basic pattern in all methods is like this (for the complete source of the class see the attached file):

image

Hope this helps someone!

 

Attached source

ObservableTest.zip

Comments are closed.