Reputation: 109
Let's say I have a ComboBox
named comboBox
.
I want to disable ComboBox
's auto complete feature.
At first I thought that everything I need to do is setting its IsTextSearchEnabled
to false
as following
comboBox.IsTextSearchEnabled = false;
But it seems doing this cause some unexpected side effects.
When IsTextSearchEnabled = true
(which is default with combobox) if you try to set a value for ComboBox
's Text
, the combobox will find corresponding index in its ItemsSource
and update the its SelectedIndex
accordingly.
List<string> lst = new List<string>();
lst.Add("1");
lst.Add("2");
lst.Add("3");
lst.Add("4");
lst.Add("5");
MessageBox.Show(comboBox.SelectedIndex.ToString()); // -1
comboBox.ItemsSource = lst;
comboBox.Text = "3";
MessageBox.Show(comboBox.SelectedIndex.ToString()); // 2
Now when I tried to set IsTextSearchEnabled = false
, the ComboBox
's SelectedIndex
doesn't get updated when its Text
changes.
List<string> lst = new List<string>();
lst.Add("1");
lst.Add("2");
lst.Add("3");
lst.Add("4");
lst.Add("5");
MessageBox.Show(comboBox.SelectedIndex.ToString()); // -1
comboBox.IsTextSearchEnabled = false;
comboBox.ItemsSource = lst;
comboBox.Text = "3";
MessageBox.Show(comboBox.SelectedIndex.ToString()); // -1
I wonder if there is a way to achieve both (i.e disabling Auto Complete feature and still have ComboBox update its SelectedIndex automatically when its Text is changed)
Upvotes: 1
Views: 97
Reputation: 7325
There are several ways to reach it. In your case with strings it's enough to set not the Text
property, but SelectedValue
:
List<string> lst = new List<string>();
lst.Add("1");
lst.Add("2");
lst.Add("3");
lst.Add("4");
lst.Add("5");
MessageBox.Show(comboBox.SelectedIndex.ToString()); // -1
comboBox.IsTextSearchEnabled = false;
comboBox.ItemsSource = lst;
comboBox.SelectedValue = "3";
MessageBox.Show(comboBox.SelectedIndex.ToString()); // 2
If you have more complex data type as string, then you can set also SelectedValuePath
or search it by yourself in ItemsSource
in event handler for TextInput
and set the ´SelectedItem´.
Upvotes: 1