1
votes

The Problem: I cannot enter custom text to the ComboBox and press Enter to close the dropdown list, because my written custom-text is overwritten by the selected item from the dropdown list.

I use an editable=true and isTextSearchEnabled=true ComboBox with a list of strings:

<ComboBox 
   IsEditable="True" 
   IsTextSearchEnabled="True"
   ItemsSource="{Binding Names}"
   SelectedItem="{Binding SelectedName}"
   Text="{Binding Name}"
   >
   <ComboBox.Style>
     <Style>
         <EventSetter Event="TextBoxBase.TextChanged" 
                    Handler="cmbTextField_TextChanged" />
     </Style>
   </ComboBox.Style>
</ComboBox>

TextChanged: Opens the combobox dropdown list if the text is changed

private void cmbTextField_TextChanged(object sender, TextChangedEventArgs e)
{
    var cmbx = sender as ComboBox;
    //Open the dropdwon 
    cmbx.IsDropDownOpen = true;       
}

How-to get the problem:

  1. Enter the first letter e.g.: "A". -> it opens the dropdown list and selects the first Name which starts with A.
  2. Type some additional letters to the end of the found name (to get a new string which is not in the list)
  3. Press Enter -> dropdown window is closed and my custom text is overwritten with the selected text from the list.

(But it is working correctly if I press TAB instead of Enter) Does anyone know how to solve this issue?

  1. Update: The problem seems to be related to the IsTextSearchEnabled=true property.
2

2 Answers

2
votes

You can trying subscribing to the OnPreviewKeyDown method, which will fire before the key press is processed. When the method is called you can check if the key pressed was return and mark it as handled.

Something along this lines should do it:

private void cmbTextField_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
    if (e.KeyData == Keys.Return) { 
        e.Handled = true;
    }
}

Bear in mind this code wasn't tested.

1
votes

I know that's a long time since the post but I solved it by register to event: SelectionChanged and close the dropdown menu:

private void Combobox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cb = sender as ComboBox;
    cb.IsDropDownOpen = false;
}