Bind to a Collection and Display Information Based on Selection

How to: Bind to a Collection and Display Information Based on Selection

 

In a simple master-detail scenario, you have a data-bound ItemsControl such as a ListBox. Based on user selection, you display more information about the selected item. This example shows how to implement this scenario.

Example

In this example, People is an ObservableCollection<T> of Person classes. This Person class contains three properties: FirstName, LastName, and HomeTown, all of type string.

The ContentControl uses the following DataTemplate that defines how the information of a Person is presented:

The following is a screenshot of what the example produces. The ContentControl shows the other properties of the person selected.

Binding to a collection

The two things to notice in this example are:

  1. The ListBox and the ContentControl bind to the same source. The Path properties of both bindings are not specified because both controls are binding to the entire collection object.

  2. You must set the IsSynchronizedWithCurrentItem property to true for this to work. Setting this property ensures that the selected item is always set as the CurrentItem. Alternatively, if the ListBox gets it data from a CollectionViewSource, it synchronizes selection and currency automatically.

Note that the Person class overrides the ToString method the following way. By default, the ListBox calls ToString and displays a string representation of each object in the bound collection. That is why each Person appears as a first name in the ListBox.

Show:
© 2016 Microsoft