Search code examples
wpfcomboboxtext-search

How to do text search in DropDown of ComboBox with IsEditable=false


I have a ComboBox with IsEditable = false. When the user drops down the list, I'd like to support him in searching for the right item, by scrolling to the first item that fits to a letter the user types.

So when the DropDown is open and the user types 'S', I'd like him to scroll to the first item (in my case: customer) whose name starts with 'S'.

I can't use the built-in text search because the ComboBox's IsEditable is false. The user can only select one of the proposed values (customers).

How can I do text search anyway? Here is my code:

<ComboBox x:Name="cmbCustomer" 
        ItemsSource="{Binding LstAllCustomers, Mode=TwoWay}"
        SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
        ItemContainerStyle="{StaticResource customerListStyle}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Margin="2" Text="{Binding ID}"/>
                <TextBlock Margin="2" Text="{Binding LastName}"/>
                <TextBlock Margin="2" Text="{Binding FirstName}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Solution

  • Set the IsTextSearchEnabled property to true and the TextSearch.TextPath attached property to either "LastName" or"FirstName" or whatever your property is called:

    <ComboBox x:Name="cmbCustomer" 
                  ItemsSource="{Binding LstAllCustomers, Mode=TwoWay}"
                  SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"
                  ItemContainerStyle="{StaticResource customerListStyle}"
                  IsTextSearchEnabled="True" TextSearch.TextPath="LastName">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Margin="2" Text="{Binding ID}"/>
                    <TextBlock Margin="2" Text="{Binding LastName}"/>
                    <TextBlock Margin="2" Text="{Binding FirstName}"/>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
    

    This should work even if you don't set the IsEnabled property to true, assuming that your Customer class actually has a LastName property.