* Reset branch for WPF changes * Convert BMP to PNG; fix link-out-of-scope err * Add snippets for WPF... 6794 files!!!! * Add missing snippets * update file updated between migration * Fix paths to include * update breadcrumb and toc * fix index links * fix index links * fix index links * fix markdown
3.8 KiB
title, description, ms.date, dev_langs, helpviewer_keywords, ms.assetid
| title | description | ms.date | dev_langs | helpviewer_keywords | ms.assetid | ||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| How to: Bind to a Collection and Display Information Based on Selection | Follow this example to find out how to bind to a collection and display information based on selection in the Windows Presentation Foundation (WPF). | 03/30/2017 |
|
|
952a7d76-dd29-49e5-86f5-32c4530e70eb |
How to: Bind to a Collection and Display Information Based on Selection
In a simple master-detail scenario, you have a data-bound xref:System.Windows.Controls.ItemsControl such as a xref:System.Windows.Controls.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 xref:System.Collections.ObjectModel.ObservableCollection%601 of Person classes. This Person class contains three properties: FirstName, LastName, and HomeTown, all of type string.
[!code-xamlCollectionBinding#Source]
[!code-xamlCollectionBinding#UI]
The xref:System.Windows.Controls.ContentControl uses the following xref:System.Windows.DataTemplate that defines how the information of a Person is presented:
[!code-xamlCollectionBinding#DetailTemplate]
The following is a screenshot of what the example produces. The xref:System.Windows.Controls.ContentControl shows the other properties of the person selected.
The two things to notice in this example are:
-
The xref:System.Windows.Controls.ListBox and the xref:System.Windows.Controls.ContentControl bind to the same source. The xref:System.Windows.Data.Binding.Path%2A properties of both bindings are not specified because both controls are binding to the entire collection object.
-
You must set the xref:System.Windows.Controls.Primitives.Selector.IsSynchronizedWithCurrentItem%2A property to
truefor this to work. Setting this property ensures that the selected item is always set as the xref:System.Windows.Controls.ItemCollection.CurrentItem%2A. Alternatively, if the xref:System.Windows.Controls.ListBox gets it data from a xref:System.Windows.Data.CollectionViewSource, it synchronizes selection and currency automatically.
Note that the Person class overrides the ToString method the following way. By default, the xref:System.Windows.Controls.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 xref:System.Windows.Controls.ListBox.
[!code-csharpCollectionBinding#ToString] [!code-vbCollectionBinding#ToString]
