I have a tree view in which the ItemsSource is an ObservableCollection. I am dynamically loading the children contents every time the user expands the subtree by using a background worker and modifying the underlying ObservableCollection that corresponds to the children nodes. However, when I try to modify this ObservableCollection inside that thread, it will fail IF AND ONLY IF the tree is already expanded (meaning that if the number of children is small, then it will correctly populate).
What I am hoping to achieve is once I expand the tree, I can see children being dynamically populated as they get processed. How can I achieve that behavior using ObservableCollection?
The problem is that you aren’t allowed to update a collection on a background thread in WPF. The binding system will automatically marshal most simple bindings to the UI thread, but not collections. You have two options.
You can marshal the call to add the data back onto the UI thread using
Dispatcher.InvokeorDispatcher.BeginInvoke. This will allow the data to be added, but not cause a cross thread exception when WPF updates the binding.(If you’re using .NET 4.5) You can use the new EnableCollectionSynchronization on the binding to allow cross-thread access to the collection.