#1,010 – ComboBox Data Binding Basics, Part II

When using data binding, you specify the collection of items to fill the ComboBox by setting the ItemsSource property.

You can also bind the currently selected item in the ComboBox to an instance of an object in code.  You do this by binding the SelectedItem property to a property in your code that represents an instance of the appropriate type.  When the user selects an item in the ComboBox, the corresponding object is updated to refer to the selected object.

Assume that we have the following in our code behind:

  • Actor class, representing an actor
  • ActorList property, which is an ObservableCollection<Actor>
  • SelectedActor property, of type Actor

In the example below, we bind the ComboBox to the list of actors and the currently selected actor to the SelectedActor property.  As we select an actor, the Label updates, since it also binds to SelectedActor.

        <ComboBox ItemsSource="{Binding ActorList}" Margin="20"
                  SelectedItem="{Binding SelectedActor}"/>
        <Label Content="{Binding SelectedActor.NameAndDates}"/>