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 wheth开发者_Python百科er 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
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.
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
精彩评论