#975 – SelectedValue and SelectedValuePath for a ListBox

You can set the SelectedValuePath property of a ListBox to the desired property of each item in the list that should be bound to the SelectedValue property.

For example, suppose that we store a collection of Actor objects in a ListBox, e.g. by using data binding to bind the items in the ListBox to a collection of Actor objects.  We can then do the following:

  • Set SelectedValuePath to “FullName” — a property of Actor
  • Use data binding to set SelectedValue to “SelectedActor” property of the data context

Now when the user selects an item in the list, the SelectedActor property in our data context will be set to the FullName of the selected actor.

        <ListBox Margin="15" Width="200" Height="150"
                 ItemsSource="{Binding ActorList}"
                 SelectedValuePath="FullName"
                 SelectedValue="{Binding SelectedActor}"/>
        <TextBlock Text="{Binding SelectedActor}"
                   HorizontalAlignment="Center"/>

975-001

Advertisements