#1,013 – Typing Text to Select an Item in a ComboBox

If a ComboBox has focus, you can just type some text in order to select an item.  By default, the text that you enter will be matched against the property specified by the DisplayMemberPath property, or by the value of the bound object’s ToString method, if DisplayMemberPath is not specified.

In the example below, we don’t specify DisplayMemberPath, but instead specify an ItemTemplate.  If the ComboBox has focus and we start typing, the ToString method of the underlying Actor object is used to determine the object to navigate to.

        <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>

If we’ve defined Actor.ToString() to return the actor’s name in a LastName, FirstName format, we can then navigate to an actor by typing their last name.  For example, entering “L” might select Hedy Lamarr.

1013-001

Advertisements