群友提问:
C#纯小白票友,求一个WPF的combobox自动完成。就是在文本框输入字符(包括中文),下拉框的自动过滤出符合条件的项目列表?
01—实现思路
首先combobox默认是不允许编辑的,需要打开编辑功能那个需要.
IsEditable="True"我这里以dev的控件ComboBoxEdit进行示范
step1:打开vs,创建一哥应用程序,我这里命名为ControlTest;
step2:定义数据模型,我这里定义为一个枚举量(如果是类的话会更容易点)
public enum HumanSkinColors{//Yellow = 0,//White =1,//Black = 2黄色 = 0,白色 = 1,黑色 = 2}
群友特意提到中文,那枚举量就给个中文吧
step3: 定义枚举集合并实例化
public ObservableCollection<HumanSkinColors> HumanSkinList { get; set; } = new ObservableCollection<HumanSkinColors>();step4:编写方法,将枚举量添加到集合中
private void BindingEnumData(){foreach (HumanSkinColors HumanSkinColor in Enum.GetValues(typeof(HumanSkinColors))){HumanSkinList.Add(HumanSkinColor);}}
step5:绑定数据源到控件
ComboBoxCtr.ItemsSource = HumanSkinList;step6:在KeyUp事件中进行输入匹配,匹配不到就重新绑定全部枚举量
private void ComboBoxCtr_KeyUp(object sender, KeyEventArgs e){string str = ComboBoxCtr.Text.ToString();HumanSkinList.Clear();//先清空集合,再重新绑定数据if (string.IsNullOrEmpty(str)){BindingEnumData();return;}foreach (HumanSkinColors HumanSkinColor in Enum.GetValues(typeof(HumanSkinColors))){var enumStr = HumanSkinColor.ToString();if(enumStr.Contains(str))HumanSkinList.Add(HumanSkinColor);}if (HumanSkinList.Count > 0){ComboBoxCtr.ItemsSource = HumanSkinList;}else{BindingEnumData();//没有匹配到就绑定所有数据}}
完整代码
using System;using System.Collections.ObjectModel;using System.Windows;using System.Windows.Input;namespace ControlTest{/// <summary>/// MainWindow.xaml 的交互逻辑/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}public ObservableCollection<HumanSkinColors> HumanSkinList { get; set; } = new ObservableCollection<HumanSkinColors>();private void Grid_Loaded(object sender, RoutedEventArgs e){BindingEnumData();ComboBoxCtr.ItemsSource = HumanSkinList;}private void BindingEnumData(){foreach (HumanSkinColors HumanSkinColor in Enum.GetValues(typeof(HumanSkinColors))){HumanSkinList.Add(HumanSkinColor);}}private void ComboBoxCtr_KeyUp(object sender, KeyEventArgs e){string str = ComboBoxCtr.Text.ToString();HumanSkinList.Clear();//先清空集合,再重新绑定数据if (string.IsNullOrEmpty(str)){BindingEnumData();return;}foreach (HumanSkinColors HumanSkinColor in Enum.GetValues(typeof(HumanSkinColors))){var enumStr = HumanSkinColor.ToString();if(enumStr.Contains(str))HumanSkinList.Add(HumanSkinColor);}if (HumanSkinList.Count > 0){ComboBoxCtr.ItemsSource = HumanSkinList;}else{BindingEnumData();//没有匹配到就绑定所有数据}}}public enum HumanSkinColors{//Yellow = 0,//White =1,//Black = 2黄色 = 0,白色 = 1,黑色 = 2}}
02—效果演示
