如何让我的可编辑组合框接受和保留用户输入,同时动态更新组合框中可用的选项?
我想要完成的是允许用户开始输入查询,并根据迄今为止输入的内容显示查询建议。获取建议和更新组合框的内容进展顺利,但在每次更新时,输入都会被删除并替换为更新列表中的第一个条目。
到目前为止,这是我尝试过的(以及其他没有完全成功的类似 SO 建议)
<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;
}