WPF组合框';s选择的索引不';将其IsTextSearchEnabled设置为false后,不会更改

WPF组合框';s选择的索引不';将其IsTextSearchEnabled设置为false后,不会更改,wpf,combobox,autocomplete,Wpf,Combobox,Autocomplete,假设我有一个名为ComboBox的ComboBox 我想禁用组合框的自动完成功能 起初,我认为我需要做的一切就是将其IsTextSearchEnabled设置为false,如下所示 comboBox.IsTextSearchEnabled = false; 但这样做似乎会引起一些意想不到的副作用 当IsTextSearchEnabled=true(这是combobox的默认值)如果尝试为combobox的文本设置一个值,combobox将在其项资源中找到相应的索引,并相应地更新其所选索引 Li

假设我有一个名为
ComboBox
ComboBox

我想禁用组合框的自动完成功能

起初,我认为我需要做的一切就是将其
IsTextSearchEnabled
设置为
false
,如下所示

comboBox.IsTextSearchEnabled = false;
但这样做似乎会引起一些意想不到的副作用

IsTextSearchEnabled=true
(这是combobox的默认值)如果尝试为
combobox
文本设置一个值,combobox将在其
项资源中找到相应的索引,并相应地更新其
所选索引

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

我想知道是否有一种方法可以同时实现这两种功能(即禁用自动完成功能,并且当文本发生更改时,ComboBox仍会自动更新其SelectedIndex)

有几种方法可以实现。在使用字符串的情况下,设置
Text
属性,而设置
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
List lst=new List();
第1条添加(“1”);
第1条添加(“2”);
第1条添加(“3”);
第1条添加(“4”);
第1条添加(“5”);
MessageBox.Show(comboBox.SelectedIndex.ToString());//-1.
comboBox.IsTextSearchEnabled=false;
comboBox.ItemsSource=lst;
comboBox.SelectedValue=“3”;
MessageBox.Show(comboBox.SelectedIndex.ToString());//2.
如果将更复杂的数据类型设置为字符串,则还可以设置
SelectedValuePath
,或在事件处理程序中的
ItemsSource
中自己搜索
TextInput
,并设置“SelectedItem”

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