目前很多的Client都是基于JS的,但是总有时候会遇到其他的框架不如Qt、WPF和JavaFx等。那么这次我就讲解一个WPF的技巧:如何自定义隐藏下拉框选项
demo.xaml
<ComboBox IsTextSearchEnabled="False"
IsEditable="True"
ItemsSource="source" <!--source {value:string, text:string }-->
KeyUp="comboBox_KeyUp" DropDownOpened="OnDropDownOpened" DropDownClosed="OnDropDownClosed"
demo.xaml.cs
/// <summary>
/// 搜索条件过滤
/// </summary>
private void comboBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
var combobox = (ComboBox)sender;
combobox.SelectedItem = null;
var ctb = combobox.Template.FindName("PART_EditableTextBox", combobox) as TextBox;
if (ctb == null) return;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control) || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
return;
var caretPos = ctb.CaretIndex;
combobox.IsDropDownOpen = true;
var datasource = (combobox.ItemsSource as List<SelectOption>).DeepClone().Where(x => /*自定义条件*/)).ToList();
combobox.ItemsSource = datasource;
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(combobox.Items);
itemsViewOriginal.Filter = ((o) =>
if (String.IsNullOrEmpty(combobox.Text))
return true;
if (((SelectOption)o).text.ToLower().Contains(combobox.Text.ToLower()))//(SelectOption)o).text.StartsWith(combobox.Text, true, null)
return true;
return false;
itemsViewOriginal.Refresh();
ctb.CaretIndex = caretPos;
/// <summary>
/// 下拉框初始化过滤
/// </summary>
private void OnDropDownOpened(object sender, EventArgs e)
var cb = (ComboBox)sender;
if (cb.IsDropDownOpen == true)
var combobox = (ComboBox)sender;
//combobox.SelectedItem = null;
var ctb = combobox.Template.FindName("PART_EditableTextBox", combobox) as TextBox;
if (ctb == null) return;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control) || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
return;
var caretPos = ctb.CaretIndex;
combobox.IsDropDownOpen = true;
var tempValue = combobox.SelectedValue;
var datasource = (combobox.ItemsSource as List<SelectOption>).DeepClone()
.Where(x => /*自定义条件*/)
.ToList();
combobox.ItemsSource = datasource;
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(combobox.Items);
itemsViewOriginal.Refresh();
combobox.SelectedValue = tempValue;
ctb.CaretIndex = caretPos;
/// <summary>
/// 下拉框数据源还原
/// </summary>
private void OnDropDownClosed(object sender, EventArgs e)
var cb = (ComboBox)sender;
if (cb.IsDropDownOpen == false)
var tempValue = cb.SelectedValue;
cb.ItemsSource = (this.DataContext as /*定义的前端ViewModel*/).source;
cb.SelectedValue = tempValue;