WPF Difference between ObservableCollection and List
ObservableCollection can implements INotifyCollectionChanged, INotifyPropertyChanged so that it can send the update message to dependency property UI controls. In this code snippet, gui_studentListBox is a WPF ListBox control and it’s data context is set with new StudentInformationCollection(); When you click on add button, a new record has been inserted into the data context. No matter StudentInformationCollection is derived from List or ObservableCollection. But it would be updated in the ListBox UI only if you derive it from ObservableCollection. If you use List, you have reset the datacontext of WPF ListBox each and every time you make changes to the collection.
public class StudentInformationCollection : ObservableCollection<StudentInformation>
{
}
public class StudentInformationCollection : List<StudentInformation>
{
}
public StudentInformationWindow()
{
InitializeComponent();
gui_studentListBox.DataContext = new StudentInformationCollection();
}
private void Add_Click(object sender, RoutedEventArgs e)
{
StudentInformationCollection collection = (StudentInformationCollection) gui_studentListBox.DataContext;
collection.Add(new StudentInformation() { Name = "Kathir", City = "San Francisco" });
}
|