How to limit user input in combobox so that you can only enter words in the collection?

To clarify, I have a combobox with an observable collection associated with the itemsource property. I want the user to be able to enter only those elements that are present in the collection. keeping

IsTextSearchEnabled="true" 

Functionality. So I was looking online for an example of how to do this. So far, I decided that I should use

  <ComboBox TextInput="cbb1_TextInput" /> 

Event, then search the collection. But my weak attempt cannot save the autocomplete function, selectedindex becomes messy and other undesirable behavior. Since I'm pretty busy with wpf, I wonder if there are solutions that use only part of XAML?

EDIT: I tried something like this:

  private void fase1cbb1_KeyUp(object sender, KeyEventArgs e) { ComboBox cb = (ComboBox)sender; bool match = false; TextBox tb = (TextBox)cb.Template.FindName("PART_EditableTextBox", cb); if (tb.Text.Length > 0) { foreach (MenuItem MI in cb.Items) { if (MI.Text.StartsWith(tb.Text)) { match = true; ; } } if (!match) { int len = tb.Text.Length; if (len > 0) { tb.Text = tb.Text.Substring(0, len - 1); tb.SelectionStart = len; } } } } 

But as soon as there is no match, there is no longer the selected item, and there is no more autocomplete / texts.

thnx for any tips or examples.

SOLUTION: WPF ComboBox with IsEditable = "True" - How can I indicate that no matches were found?

+6
source share
1 answer

If you scroll all the way down to the bottom of the ComboBox MSDN documentation, you will find that there is a very simple answer: set the ComboBox.IsEditable parameter to false. The user can still select items in the editor by entering a prefix in the field, but they can only enter values ​​that are already listed.

The disadvantage is that you do not get any normal behavior like "TextBox", in particular, you cannot copy / paste the selected item from the combo box. If this is also a problem for you, let us know, but this is typical behavior for ComboBoxs in DropDownList on Windows anyway.

+2
source

Source: https://habr.com/ru/post/895945/


All Articles