Definition:
ObservableCollection<T>
is a class in the .NET Framework that provides a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
It is part of the System.Collections.ObjectModel
namespace.
Key features of ObservableCollection<T>
:
- Dynamic Updates:
ObservableCollection<T>
automatically notifies subscribers (such as UI elements) when items are added, removed, or when the entire collection is refreshed. This makes it particularly useful in scenarios where you want the user interface to automatically reflect changes in the underlying data. - Designed for Data Binding: It’s commonly used in data binding scenarios, especially in WPF and other XAML-based frameworks, where you want the UI to stay in sync with changes in the data.
- Events:
ObservableCollection<T>
provides events such asCollectionChanged
that allow you to subscribe to changes in the collection.
An example of how ObservableCollection<T>
in a WPF application might be used:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<string> _items;
public ObservableCollection<string> Items
{
get { return _items; }
set
{
if (_items != value)
{
_items = value;
OnPropertyChanged(nameof(Items));
}
}
}
public ViewModel()
{
// Initialize the collection and add some items
Items = new ObservableCollection<string>
{
"Item 1",
"Item 2",
"Item 3"
};
// Subscribe to the CollectionChanged event
Items.CollectionChanged += (sender, e) =>
{
// Handle changes to the collection (additions, removals, etc.)
MessageBox.Show("Collection changed!");
};
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In this example:
ViewModel
has a property calledItems
of typeObservableCollection<string>
.- The constructor initializes the collection and adds some items.
- The
CollectionChanged
event is subscribed to, so whenever the collection changes, a message box is displayed.
In a WPF application, you might bind this collection to a ListBox
or another UI control, and the UI would automatically update when items are added or removed from the collection.
This is because the ListBox
is notified of changes in the ObservableCollection
, and it refreshes itself accordingly.