Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an autocomplete textbox with dropdown

My Problem:

I have a list of 118 chemical element names. And I wish to make a textbox in which as I type it will throw a dropdown menu with suggestion of names. I made this textbox in winforms and it was piece of cake however my efforts of making it in wpf are in vain. I've tried extended wpf toolkit, nimgoble and some other autocomplete textbox libs. So far dead end...I'm also new to wpf so maybe I'm missing something with these libs? I can't make them list my items and some won't even show the dropdown menu.

Heres what I wanted:

enter image description here

Here's how I finally achieved it:

So I solved this by using a combination of textbox and listbox. Where in textbox user types and as it changes (textbox changed event) it's checking for matches inside a list that holds names of all 118 elements and displays matches for the text typed in, inside listbox. Here's the code:

private void textBox_TextChanged(object sender, TextChangedEventArgs e)
    {

        listBox.Items.Clear();


        if (textBox.Text.Trim() != "")
        {
            string regexPattern = (textBox.Text.ToString()) + "\\w*";
            regexPattern = char.ToUpper(regexPattern[0]) + regexPattern.Substring(1); //prvo slovo veliko

            Match match = Regex.Match(ElementNames.allElements, regexPattern);
            while (match.Success && match.Value != "")
            {
                listBox.Items.Add(match.Value.ToString());
                listBox.Visibility = Visibility.Visible;

                match = match.NextMatch();
            }
        }

            if (listBox.Items.IsEmpty || listBox.Items.Count == 119)
            {
                listBox.Visibility = Visibility.Collapsed;
                if (listBox.Items.Count == 119) listBox.Items.Clear();
            }

        HighlightElementsOnTable();
        OtherButtonsHighlight();
        BringBackColors();
    }
like image 624
maran Avatar asked Mar 30 '16 08:03

maran


2 Answers

You can use a ComboBox with IsEditable=true.

like image 76
H.B. Avatar answered Oct 16 '22 19:10

H.B.


Use a Combobox with

  • IsEditable = true
  • SelectedItem and Text data bound to the same property
  • StaysOpenOnEdit = true
<ComboBox ItemsSource="{Binding Models}" SelectedItem="{Binding Model}" 
 IsEditable="True" StaysOpenOnEdit="True" Text="{Binding Model, UpdateSourceTrigger=PropertyChanged}"/>
like image 1
The One Avatar answered Oct 16 '22 19:10

The One