WPF之comboBox可模糊查询

前言

本文采用了prism框架的基础。

0、先准备一个类

public class ComboBoxItemModel
{
    public string Name { get; set; }
    public string Value { get; set; }
}

一、xaml代码。

前端这里需添加两个属性,还有keyUp事件等。

1、IsEditable="True"(开启可编辑)

2、IsTextSearchEnabled="False"(开启可查询)

 

二、.cs代码

YourViewModel vm;
public YourView()
{
    InitializeComponent();
    vm =new YourViewModel();
    this.DataContext = vm;
}
private void comboBoxDataS_KeyUp(object sender, KeyEventArgs e)
 {
     ComboBox comboBox=sender as ComboBox;
     this.vm.UpdateDataSComboBoxItems(comboBox.Text);
     if (this.vm.DataSList.Count>0)
     {
         comboBox.IsDropDownOpen=true;
     }
     TextBox editBox = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox);
     //每次填写后光标定位到文本后面--如果想要效果更好需加上该句
     editBox.SelectionStart=editBox.Text.Length;
 }

三、VM代码

//在初始化时,先实例化一个DataSList
DataSList = new List();

private List dataSList;
private ComboBoxItemModel selectedDataS;
public List DataSList
{
    get { return dataSList; }
    set { dataSList = value; RaisePropertyChanged(); }
}
public ComboBoxItemModel SelectedDataS
{
    get { return selectedDataS; }
    set { selectedDataS = value; RaisePropertyChanged(); }
}
//可不要,我是为了方便查询时使用
public string SelectDataS
{
    get { return selectedDataS?.Value ?? ""; }
}

//.cs内调用的方法
internal void UpdateDataSComboBoxItems(string text)
{
    text = text.Trim();
    List list = GetComboboxValue("DataS", text);//需替换成自己从数据库内取出的结果
    DataSList.Clear();
    if (list != null && list.Count != 0)
    {
        for (int i = 0; i < list.Count; i++)
        {
            DataSList.Add(new ComboBoxItemModel() { Name = list[i], Value = list[i] });
        }
    }
    else
    {
        DataSList.Add(new ComboBoxItemModel() { Name = "未匹配到结果", Value = "未匹配到结果" });
    }
    DataSList = new List(DataSList);
}

你可能感兴趣的:(WPF,wpf)