WPF Databinding to the "Selected Item"

Nate Bross

Well-known member
Joined
Apr 6, 2005
Messages
601
Location
Chicago, IL
If you have a situation where you need to have a list of "items" and then populate fields outside the list with information from the selected item, this is for you.

Basic Concept
Set the DataContext of a parent container control, and Databind "Up the tree."

Example
Code:
<Window.Resources>
<ObjectDataProvider x:Key="myList" ObjectType="{x:Type YourCollection}" />
</Window.Resources>
<Grid x:Name="mainGrid" DataContext="{Binding Source={StaticResource myList}}">
    <ListBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding}">
        // Your DataTemplate here
    </ListBox>
    <TextBlock Text="{Binding Path=/PropertyOfCollectionItem}" />
</Grid>

The key to note here is the /Item notation in the Binding of the items outside the list, and the IsSynchronizedWithCurrentItem="True" in the ListBox, and the ItemsSource="{Binding}" which says to "look up the tree" for a binding source.

What this does is make sure your bindings change with selected item changed.
 
Back
Top