【问题标题】:WPF ComboBox's SelectedIndex doesn't change after setting its IsTextSearchEnabled to falseWPF ComboBox 的 SelectedIndex 在将其 IsTextSearchEnabled 设置为 false 后不会更改
【发布时间】:2018-10-17 16:32:44
【问题描述】:

假设我有一个名为comboBoxComboBox

我想禁用ComboBox 的自动完成功能。

起初我以为我需要做的就是将其IsTextSearchEnabled 设置为false 如下

comboBox.IsTextSearchEnabled = false;

但这样做似乎会导致一些意想不到的副作用。

IsTextSearchEnabled = true(默认为组合框)时,如果您尝试为ComboBoxText 设置值,组合框将在其ItemsSource 中找到相应的索引并相应地更新其SelectedIndex .

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

现在,当我尝试设置 IsTextSearchEnabled = false 时,ComboBoxSelectedIndex 在其 Text 更改时不会更新。

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

我想知道是否有办法同时实现这两者(即禁用自动完成功能,并且 ComboBox 在其文本更改时仍会自动更新其 SelectedIndex)

【问题讨论】:

    标签: wpf combobox autocomplete


    【解决方案1】:

    有几种方法可以达到它。在您使用字符串的情况下,设置不是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
    

    如果您有更复杂的数据类型为字符串,那么您也可以设置SelectedValuePath 或在TextInput 的事件处理程序中自行搜索ItemsSource 并设置“SelectedItem”。

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多