<ComboBox x:Name="cbCustomVar" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" Height="30" ItemsSource="{Binding SpecificationVM.Specifications}" IsEditable="True" KeyUp="CbCustomVar_KeyUp"></ComboBox>
防止控件自动清空解决办法
public ObservableCollection<string> dicCustomVars { get; set; } = new ObservableCollection<string>();
string str;
private async void CbCustomVar_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
await Task.Delay(500);
str = cbCustomVar.Text.ToString();
if (string.IsNullOrEmpty(str))
{
cbCustomVar.ItemsSource = SpecificationVM.Specifications;
return;
}
dicCustomVars.Clear();
// System.Threading.Thread.Sleep(500);
foreach (var customVar in SpecificationVM.Specifications)
{
if(customVar.Contains(str))
{
dicCustomVars.Add(customVar);
}
}
cbCustomVar.ItemsSource = "";
if (dicCustomVars.Count > 0)
{
cbCustomVar.ItemsSource = dicCustomVars;
// this.cbCustomVar.SelectedIndex = -1;
}
else
{
//cbCustomVar.ItemsSource = SpecificationVM.Specifications;
}
cbCustomVar.Text=str;
cbCustomVar.IsDropDownOpen = true;
}
这篇博客介绍了如何防止ComboBox在输入时自动清空。通过创建一个ObservableCollection dicCustomVars,结合KeyUp事件处理,实现了输入时的实时搜索和过滤功能。当用户输入时,内容会与Specifications列表进行比较,只显示包含输入字符串的项。如果无匹配项,恢复显示全部列表。该方法确保了用户输入不会被意外清除,并提供了友好的搜索体验。
1527

被折叠的 条评论
为什么被折叠?



