简体   繁体   中英

How can I set the search option in combobox C#

I have combobox with country names I want to set search box to that to easily find the country how can I do that?

Here is my XAML coding of ComboBox

<ComboBox x:Name="countryComboBox" Loaded="countryComboBox_Loaded" Width="300"/>

here is C# coding

private void countryComboBox_Loaded(object sender, RoutedEventArgs e)
{
       countryComboBox.ItemsSource = GetCountries();            
}

Countries list is loading but no text area and I want to add it to easily find the country.

Something like this (may have compile errors, i write the code in Notepad not VS)

<StackPanel>
    <TextBox x:Name="searchBox" TextChanged="searchBox_TextChanged" />
    <ComboBox x:Name="countryComboBox" Loaded="countryComboBox_Loaded" Width="300"/>
</StackPanel>

List<string> countries;
private void countryComboBox_Loaded(object sender, RoutedEventArgs e)
{
   countries = GetCountries();
   countryComboBox.ItemsSource = countries;           
}

private void searchBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (searchBox.Text == "") return;

    int index = countries.FindIndex((str) => str.StartsWith(searchBox.Text));
    if (index != -1)
        countryComboBox.SelectedIndex = index;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM