#969 – Items Property of ListBox Contains List of Items
December 11, 2013 3 Comments
Deriving from an ItemsControl, a ListBox provides access to the list of items contained in the ListBox by way of its Items property. The Items property is an ItemCollection, which supports the IList and ICollection interfaces, as well as providing properties for grouping, sorting and filtering items in the collection.
Entries in the ItemCollection can be any .NET object (derives from System.Object). You’ll most often use data binding to bind the ItemsSource property of the ListBox to some sort of collection that supports IEnumerable. (E.g. an ObservableCollection). Doing this will set Items to refer to the bound collection.
You can access individual items from code using an indexer on the Items property.
private void Button_Click(object sender, RoutedEventArgs e) { // Note: Our ListBox contains instances of Actor objects Actor actor = lbMyListBox.Items[0] as Actor; if (actor != null) MessageBox.Show(string.Format("First Actor in list is: {0}", actor.FullName)); }