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

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

Using the following simple text box as an example:


    Angus/ComboBoxItem         


        
3条回答
  •  独厮守ぢ
    2021-01-05 13:52

    This solution is based on user1234567's answer, with a couple changes. Instead of searching the Items list it simply checks the ComboBox's SelectedIndex for a value >= 0 to see if a match was found and it resolves RB's concern about holding down a key inserting more than one character. It also adds an audible feedback when it rejects characters.

    private int _lastMatchLength = 0;
    
    private void myComboBox_GotFocus(object sender, RoutedEventArgs e)
    {
        _lastMatchLength = 0;
    }
    
    private void myComboBox_KeyUp(object sender, KeyEventArgs e)
    {
        ComboBox cBox = sender as ComboBox;
    
        TextBox tb = cBox.Template.FindName("PART_EditableTextBox", cBox) as TextBox;
        if (tb != null)
        {
            if (cBox.SelectedIndex >= 0)
            {
                _lastMatchLength = tb.SelectionStart;
            }
            else if (tb.Text.Length == 0)
            {
                _lastMatchLength = 0;
            }
            else
            {
                System.Media.SystemSounds.Beep.Play();
                tb.Text = tb.Text.Substring(0, _lastMatchLength);
                tb.CaretIndex = tb.Text.Length;
            }
        }
    }
    

提交回复
热议问题