ComboBox - AutoComplete + Free typing

时间:2015-06-25 18:47:10

标签: c# wpf combobox autocomplete

I want my combobox to enable the autocomplete if what the user is typing is in the items list and if it doesn't exists, I want to include it in my list. For example: A ComboBox with these items: "Rock, Country, Jazz". If the user starts typing "Ro..." the combobox autocomplete to 'Rock'. But if the user types "Blues", I want to add it to my items. So it would be like: "Rock, Country, Jazz, Blues". How can I do that?

2 个答案:

答案 0 :(得分:3)

You can use AutoCompleteMode and AutoCompleteSource for auto complete. comboBox1.AutoCompleteMode = AutoCompleteMode.Append; comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems; or you can do this via Properties Panel in Visual Studio after selecting your ComboBox... For adding new items to your ComboBox; private void comboBox1_TextChanged(object sender, EventArgs e) { if (!comboBox1.Items.Contains(comboBox1.Text)) { comboBox1.Items.Add(comboBox1.Text); comboBox1.Items.RemoveAt(comboBox1.Items.Count - 2); } }

答案 1 :(得分:1)

如果我使用MVVM这样做,我会从ComboBox开始并修改它以适应。

如果您使用ComboBox中的内置DevExpress,则几乎可以免费获得此内容。只需在下拉列表中填写您要自动完成的项目,然后设置以下选项:

  • 自动下拉(因此当您开始输入时,它会自动下拉匹配列表)。
  • 按匹配过滤列表(即下拉列表中的唯一项目将与您输入的内容相匹配)。
  • 匹配部分(即您键入的内容将过滤下拉列表,在任何地方都匹配,即使在中心)。

如果您想获得更好的体验,您可以编写一个服务来监听用户当前在框中输入的内容,然后调整下拉项列表以适应。下拉列表中与用户类型匹配的任何项目将自动显示。我会使用Reactive Extensions(RX)和Throttle来执行此操作,请参阅: