Creating and Binding to an ObservableCollection

When using an ItemsControl such as a ListBox or TreeView to display a collection of data, you need to bind to the collection and enumerate through its elements.

A collection implementing the IEnumerable interface is eligible for binding to an ItemsControl. The ObservableCollection class enables you to easily bind to collections and also provides notifications whenever you add, remove, or refresh items in the collection. Both WPF and Silverlight support this class. It is defined in the System.Collections.ObjectModel namespace and implements the INotifyCollectionChanged interface.

For example, to bind to a collection of cities, you can use the following XAML markup and code:

XAML Markup:

<Grid x:Name="LayoutRoot"> ...

Get XAML Developer Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.