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

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

Using the following simple text box as an example:


    Angus/ComboBoxItem         


        
3条回答
  •  误落风尘
    2021-01-05 13:49

    This is a good solution until you have a lot of records in the combo box. I would do it this way:

    Declare this at the top of the file

    List items = new List(); 
    
    private void myComboBox_KeyUp(object sender, KeyEventArgs e) 
    { 
      TextBox textBox = myComboBox.Template.FindName("PART_EditableTextBox", myComboBox) as TextBox; 
    
         // indicates whether the new character added should be removed 
        bool shouldRemove = true; 
    
        // this way you don't fill the list for every char typed
        if(items.Count <= 0)
        { 
           for (int i = 0; i < myComboBox.Items.Count; i++) 
           { 
               items.Add(((ComboBoxItem)myComboBox.Items.GetItemAt(i)).Content.ToString()); 
           } 
        }
        // then look in the list
        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; 
        } 
    } 
    

    unless the binding is continue adding records to the combo box, I think is a more efficient lookup

提交回复
热议问题