Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing an ObservableCollection

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

like image 565
Ben Foster Avatar asked Dec 07 '25 09:12

Ben Foster


1 Answers

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.

like image 188
Joe White Avatar answered Dec 10 '25 12:12

Joe White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!