3
votes

In a WPF app I have a ListView bound to an ObservableCollection on my ViewModel.

During the running of the application I need to remove and reload all the items in the collection. I do not ever need to add or remove single items.

This prompts the question whether an ObservableCollection is really necessary and whether I could just bind the ListView to an IEnumerable and call OnPropertyChanged when the collection is replaced?

Since ObservableCollection does not have an AddRange method, the only way of reloading without replacing the collection would be to add each item individually. Is this likely to have any major performance implications since CollectionChanged is fired for each item added?

Finally, since I am using ICollectionView to synchronize the currently selected item, if I do replace the collection, will I need to call CollectionViewSource.GetDefaultView again? I assume I can reuse the existing CurrentChanged handler.

Thanks Ben

2
I tested this formerly. ObservableCollection is faster than List with notification.vortexwolf
@vorrtex - any stats to back this up? And does this apply in my case where I am looking at replacing the entire collection?Ben Foster
Just try it youself using class Stopwatch. The performance problem exists only with displaying items, and a number of items won't change anything because of UI virtualization.vortexwolf

2 Answers

5
votes

I would say your intuition is correct: if you never add or remove individual items, but always swap out the entire list, and you're fairly sure that requirement isn't going to change, then you're better off with a non-observable list (or IEnumerable) and INotifyPropertyChanged.

If the lists are large, this would gain you some speed. But the big benefit is readability: it would more clearly express your intention. The next person to maintain your code won't run around trying to find all the code that could ever add and remove elements from the ObservableCollection; they'll be able to quickly and clearly see that you always swap out the whole list.

1
votes

My answer is it depends.

If your collection can go over 10000 objects I'll say its better to avoid 10000 events of collection changed and replace them with one property changed.

The best solution here is to implement your own behavior by inherit from list and implement INCC as you need it to work.

If you choose to use a simple IEnumerable you'll need to ask for DefualtView each time the reference change