#1,011 – ComboBox Data Binding Basics, Part III

To display the items in a ComboBox using something more than a simple string, you set the ItemTemplate of the ComboBox to define the layout of each item.  When you set the ItemTemplate, you don’t set the DisplayMemberPath property.  DisplayMemberPath defines the template for each item in the ComboBox to be a TextBlock that displays a single string.

Below, we set an item template for a ComboBox that binds to a collection of Actor objects so that we display an image and some information about the actor, for each item.

        <ComboBox ItemsSource="{Binding ActorList}" Margin="20"
                  SelectedItem="{Binding SelectedActor}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Image}" Height="100"/>
                        <StackPanel Margin="10,0">
                            <TextBlock Text="{Binding FullName}" FontWeight="Bold" />
                            <TextBlock Text="{Binding Dates}"/>
                            <TextBlock Text="{Binding KnownFor}" FontStyle="Italic"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <Label Content="{Binding SelectedActor.NameAndDates}"/>

As we select an item, notice that the ComboBox changes size, so that the surface can show the entire item.

1011-001

1011-002

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #1,011 – ComboBox Data Binding Basics, Part III

  1. Pingback: Dew Drop – February 18, 2014 (#1725) | Morning Dew

  2. Rock says:

    I cut and paste you code to a sample project but was unable to set the selected item in my view model. It display the test and image and also I can hit the drop list and select the item. Do you have a sample project to

    • Sean says:

      Does the property that you’re binding to have the same data type as the items in the list? Is it in the same data context? Are you getting any binding errors at runtime? Are you properly setting the data context of the view to your ViewModel and does the ViewModel fully implement IPropertyNotify?

  3. PC says:

    All ok but in this tutorial C# code is missing. Could you put the code how to bind all these elements from database?

    Thanks

Leave a comment