ObservableCollection

·

·

1–2 minutes

In WPF, we can bind an ObservableCollection<T> object to the ItemsSource property of an ItemsControl, e.g. a ComboBox. When we add or remove an element from the collection, the control bound to the collection will get updated automatically. However, we modify an element of the collection, the control won’t get updated. To force the control gets updated when an element of the collection it is bound to, we need to write a class inheriting from ObservableCollection<T> and provide a method that calls the OnCollectionChanged() method, which raises the CollectionChanged event, which will caused the control bound to the collection to be refreshed.

public class ElementCollection<T> : ObservableCollection<T>
{
  public void UpdateCollection()
  {
    OnCollectionChanged(new NotifyCollectionChangedEventArgs(
        NotifyCollectionChangedAction.Reset));
  }
}

Then we change the type of the collection to ElementCollection, and call the UpdateCollection() method after we changed the value of an element.

Related Articles

Get updates

Spam-free subscription, we guarantee. This is just a friendly ping when new content is out.

Go back

Your message has been sent

Warning
Warning
Warning.

Leave a comment