BindableCollection
BindableCollection<T> is INotifyCollectionChanged
implementation that updates the UI on add and remove of items.
In WinUI for Desktop, BindableCollection<T>
inherits the ObservableCollection<T>
and both classes have the same logic. In WinUI for UWP, the BindableCollection<T>
implements the INotifyCollectionChanged
interface from scratch. This was needed because of a limitation in UWP where, the ObservableCollection<T>
doesn't update the UI in some situations.
The BindableCollection<T>
provides the same set of features as Collection<T>
, like Add
and Remove
methods. The features specific for this type of collection are its Move
method and the CollectionChanged
event.
The Move
method allows you to move an item from one index in the collection to another.
Example 1: Move method usage
ObservableCollection<int> collection = new ObservableCollection<int>();
for (int i = 0; i < 10; i++)
{
collection.Add(i);
}
//items order BEFORE the Move call: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
collection.Move(2, 7);
//items order AFTER the Move call: 0, 1, 3, 4, 5, 6, 7, 2, 8, 9
CollectionChanged
event is raised whenever a change appears in the collection items. This may include add, remove, replace, move or reset of the items.
Example 2: CollectionChanged event usage
public InitializeCollection()
{
ObservableCollection<int> collection = new ObservableCollection<int>();
collection.CollectionChanged += Collection_CollectionChanged;
}
private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
}