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"(开启可查询)

 <ComboBox
     x:Name="comboBoxDataS"
     Width="150"
     Margin="15,5"
     md:HintAssist.Hint="请选择……"
     DisplayMemberPath="Name"
     IsEditable="True"
     IsTextSearchEnabled="False"
     ItemsSource="{Binding DataSList}"
     KeyUp="comboBoxDataS_KeyUp"
     SelectedItem="{Binding SelectedDataS}"
     SelectedValuePath="Value" />

二、.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<ComboBoxItemModel>();

private List<ComboBoxItemModel> dataSList;
private ComboBoxItemModel selectedDataS;
public List<ComboBoxItemModel> 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<string> 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<ComboBoxItemModel>(DataSList);
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值