#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"));
        }

970-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #970 – Avoid Working Directly with Items Collection

  1. Pingback: Dew Drop – December 12, 2013 (#1682) | Morning Dew

  2. Pingback: Dew Drop – December 13, 2013 (#1683) | Morning Dew

Leave a comment