WPF ComboBox with IsEditable=“True” - How can I indicate that no match was found?

前端 未结 3 741
无人共我
无人共我 2021-01-05 12:57

Using the following simple text box as an example:


    Angus/ComboBoxItem         


        
3条回答
  •  花落未央
    2021-01-05 13:29

    As a starter, you might want to let the user see if they are typing in one of the available options.

    1) Search "autocomplete combobox" online.

    2) Check these out:

    http://weblogs.asp.net/okloeten/archive/2007/11/12/5088649.aspx

    http://www.codeproject.com/KB/WPF/WPFCustomComboBox.aspx

    3) Also try this:

        
            
            
        
    

    The above code snippet is a primite way to provide that "visual indication" you're looking for. If the user types in 'h', then 'hello' will appear in the input textbox. However, this on its own won't have a mechanism to stop the user from typing in an illegal character.

    4) This is a more advanced version:

        
            
            
            
            
        
    

    Code-behind:

        private void myComboBox_KeyUp(object sender, KeyEventArgs e)
        {
            // Get the textbox part of the combobox
            TextBox textBox = myComboBox.Template.FindName("PART_EditableTextBox", myComboBox) as TextBox;
    
            // holds the list of combobox items as strings
            List items = new List();
    
            // indicates whether the new character added should be removed
            bool shouldRemove = true;
    
            for (int i = 0; i < myComboBox.Items.Count; i++)
            {
                items.Add(((ComboBoxItem)myComboBox.Items.GetItemAt(i)).Content.ToString());
            }
    
            for (int i = 0; i < items.Count; i++)
            {
                // legal character input
                if(textBox.Text != "" && items.ElementAt(i).StartsWith(textBox.Text))
                {
                    shouldRemove = false;
                    break;
                }
            }
    
            // illegal character input
            if (textBox.Text != "" && shouldRemove)
            {
                textBox.Text = textBox.Text.Remove(textBox.Text.Length - 1);
                textBox.CaretIndex = textBox.Text.Length;
            }
        }
    

    Here, we don't let the user continue typing in once we detect that no combobox item starts with the text in the textbox. We remove the character added and wait for another character.

提交回复
热议问题