WPF可编辑的组合框-在更新可观察列表时保留输入

本文关键字:列表 观察 保留 输入 更新 编辑 组合 WPF | 更新日期: 2023-09-27 18:11:39

如何让我的可编辑组合框既接受并保留用户输入,同时动态更新组合框中的可用选项?

我想要实现的是允许用户开始输入查询,并根据目前输入的内容显示查询建议。获取建议和更新comobobbox的内容进展顺利,但每次更新时,输入都会被清除并替换为更新列表中的第一个条目。

这是我到目前为止尝试过的(以及其他类似的建议,但没有完全成功)

<ComboBox x:Name="cmboSearchField" Margin="197,10,0,0" 
 VerticalAlignment="Top" Width="310" IsTextSearchEnabled="True" 
 IsEditable="True" ItemsSource="{Binding SearchTopics}" 
 KeyUp="GetSearchTopics"/>

和我的代码后面:

public ObservableCollection<string> SearchTopics {get;set;}
void GetSearchTopics(object sender, KeyEventArgs e)
{
   bool showDropdown = this.cmboSearchField.IsDropDownOpen;
   if ((e.Key >= Key.D0) && (e.Key <= Key.Z))
   {
      query = this.cmboSearchField.Text;
      List<string> topics = GetQueryRecommendations(query);
      _searchTopics.Clear();
      _searchTopics.Add(query); //add the query back to the top
      //stuffing the list into a new ObservableCollection always
      //rendered empty when the dropdown was open          
      foreach (string topic in topics)
      {
         _searchTopics.Add(topic);
      }
      this.cmboSearchField.SelectedItem = query; //set the query as the current selected item
      //this.cmboSearchField.Text = query; //this didn't work either   
      showDropdown = true;
   }

   this.cmboSearchField.IsDropDownOpen = showDropdown;
}

WPF可编辑的组合框-在更新可观察列表时保留输入

你不应该清除observablecollection

如果您清除集合,那么在某个时刻列表将为空,并且对selecteditem的引用将丢失。

相反,只需查看哪些项目已经在那里,并且只添加那些尚未可用的项目。

事实证明,更新ObservableCollection与我所看到的行为无关。后来我意识到,它的行为就好像输入是在搜索下拉集合中的匹配条目,从而替换用户每次提供的任何输入。

这正是发生的事情。在窗口XAML中设置ComboBox元素的IsTexSearchEnabled属性为false解决了这个问题。

<ComboBox x:Name="cmboSearchField" Margin="218,10,43,0" 
 IsTextSearchEnabled="false" VerticalAlignment="Top" 
 IsEditable="True" ItemsSource="{Binding SearchTopics}" 
 KeyUp="GetSearchTopics"/>