How to refresh UI from ViewModel with ObservableCollection?
This is a good case for an extension method. It hides away the implementation in case it changes in future versions, can be modified in one place, and the calling code looks simpler and less confusing.
public static void Refresh<T>(this ObservableCollection<T> value)
{
CollectionViewSource.GetDefaultView(value).Refresh();
}
Usage:
myCollection.Refresh();
If you need to change your UI because you've edited the items in your collection, then you should arrange for those items to implement the INotifyPropertyChanged
interface. If the objects within your collection have a PropertyChanged
event, the UI will be listening for that event from individual items. (If possible, you could also change the items in your collection to be DependencyObjects
with DependencyProperties
, which accomplishes the same goal.)
If you really need to trigger a UI update when nothing at all about your collection has changed, the way to do it is to manually raise the CollectionChanged
event. This can't be done with the ObservableCollection<>
as is, but you could derive a new collection from that class, and call the protected OnCollectionChanged
method from within some new, public
method.
I've had a similar issue where I wanted to change the background on an item, but obviously neither the item nor the collection changed.
It was achieved by calling:
CollectionViewSource.GetDefaultView(your_collection_name).Refresh();
This refreshed the view from the view model without altering the collections