#970 – Avoid Working Directly with Items Collection

When you use a ListBox (or any other ItemsControl), you’ll most often populate the control by binding the ItemsSource property of the control to a collection.  The Items property of the control can then be examined, if you want to look at the individual items in the collection.

In practice, however, you’ll work directly with the collection that the ListBox is bound to, rather than working with the Items property.  For example:

  • To add items, add them to the underlying collection
  • To remove items, remove them from the underlying collection
  • To change an item, change the corresponding item in the underlying collection

The example below adds a new Actor to a bound collection when a button is clicked.  Note that the ListBox is updated immediately.

        private void Button_Click(object sender, RoutedEventArgs e)
            ActorList.Add(new Actor("Marty Feldman", 1934, 1982, "Young Frankenstein"));