using System.Collections.ObjectModel; ObservableCollectionnames = new ObservableCollection (); names.Add("Alice"); names.Add("Bob"); names.Add("Charlie");
ObservableCollectionfruits = new ObservableCollection (); fruits.CollectionChanged += (sender, args) => { if (args.Action == NotifyCollectionChangedAction.Add) { Console.WriteLine("New fruit added"); } else if (args.Action == NotifyCollectionChangedAction.Remove) { Console.WriteLine("Fruit removed"); } }; fruits.Add("Apple"); // outputs "New fruit added" fruits.Remove("Apple"); // outputs "Fruit removed"
In all the above examples, ObservableCollection is part of the System.Collections.ObjectModel namespace which is a package library provided by the .NET framework.public class MainViewModel : INotifyPropertyChanged { public ObservableCollection People { get; } = new ObservableCollection (); public MainViewModel() { // populate People collection with data } }