C#实现带搜索功能的ComboBox

带搜索的ComboBox就是给ComboBox一个依赖属性的ItemSource,然后通过数据源中是否包含要查询的值,重新给ComboBox绑定数据源。

public class EditComboBox : ComboBox
  {
    private bool t = true;//首次获取焦点标志位
    private ObservableCollection<object> bindingList = new ObservableCollection<object>();//数据源绑定List
    private string editText = "";//编辑文本内容

    /// <summary>
    /// 注册依赖事件
    /// </summary>
    public static readonly DependencyProperty ItemsSourcePropertyNew = DependencyProperty.Register("MyItemsSource", typeof(IEnumerable), typeof(EditComboBox), new FrameworkPropertyMetadata(new PropertyChangedCallback(ValueChanged)));
    /// <summary>
    /// 数据源改变,添加数据源到绑定数据源
    /// </summary>
    /// <param name="d"></param>
    /// <param name="e"></param>
    private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      EditComboBox ecb = d as EditComboBox;
      ecb.bindingList.Clear();
      //遍历循环操作
      foreach (var item in ecb.MyItemsSource)
      {
        ecb.bindingList.Add(item);
      }
    }
    /// <summary>
    /// 设置或获取ComboBox的数据源
    /// </summary>
    public IEnumerable MyItemsSource
    {
      get
      {
        return (IEnumerable)GetValue(ItemsSourcePropertyNew);
      }

      set
      {
        if (value == null)
          ClearValue(ItemsSourcePropertyNew);
        else
          SetValue(ItemsSourcePropertyNew, value);
      }
    }
    /// <summary>
    /// 重写初始化
    /// </summary>
    /// <param name="e"></param>
    protected override void OnInitialized(EventArgs e)
    {
      base.OnInitialized(e);
      this.IsEditable = true;
      this.IsTextSearchEnabled = false;
      this.ItemsSource = bindingList;
    }
    /// <summary>
    /// 下拉框获取焦点,首次搜索文本编辑框
    /// </summary>
    /// <param name="e"></param>
    protected override void OnGotFocus(RoutedEventArgs e)
    {
      if (t)
        FindTextBox(this);
      else
        t = false;
    }
    /// <summary>
    /// 搜索编辑文本框,添加文本改变事件
    /// </summary>
    /// <param name="obj"></param>
    private void FindTextBox(DependencyObject obj)
    {
      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
      {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child!=null && child is TextBox)
        {
          //注册文本改变事件
          (child as TextBox).TextChanged += EditComboBox_TextChanged;
        }
        else
        {
          FindTextBox(child);
        }
      }
    }
    /// <summary>
    /// 文本改变,动态控制下拉条数据源
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void EditComboBox_TextChanged(object sender, TextChangedEventArgs e)
    {
      TextBox tb = sender as TextBox;
      if(tb.IsFocused)
      {
        this.IsDropDownOpen = true;
        if (editText == this.Text)
          return;
        editText = this.Text;
        SetList(editText);
      }
    }
    /// <summary>
    /// 组合框关闭,数据源恢复
    /// </summary>
    /// <param name="e"></param>
    protected override void OnDropDownClosed(EventArgs e)
    {
      base.OnDropDownClosed(e);
      if (MyItemsSource == null)
        return;
      foreach (var item in MyItemsSource)
      {
        if (!bindingList.Contains(item))
          bindingList.Add(item);
      }
    }
    /// <summary>
    /// 过滤符合条件的数据项,添加到数据源项中
    /// </summary>
    /// <param name="txt"></param>
    private void SetList(string txt)
    {
      try
      {
        string temp1 = "";
        string temp2 = "";
        if (MyItemsSource == null)
          return;
        foreach (var item in MyItemsSource)
        {
          temp1 = item.GetType().GetProperty(this.DisplayMemberPath).GetValue(item, null).ToString();
          if (string.IsNullOrEmpty(this.SelectedValuePath))
          {
            temp2 = "";
          }
          else
          {
            temp2 = item.GetType().GetProperty(this.SelectedValuePath).GetValue(item, null).ToString();
          }
          if(temp1.Contains(txt)||temp2.StartsWith(txt))
          {
            if (!bindingList.Contains(item))
              bindingList.Add(item);
          }
          else if (bindingList.Contains(item))
          {
            bindingList.Remove(item);
          }
        }
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.ToString());
      }
    }
  }

调用方法就是将数据源绑定到MyItemsSource上,剩下的就和原有的ComboBox用法一样了。

代码如下:

<local:EditComboBox MyItemsSource="{Binding ProList,Mode=TwoWay}" SelectedItem="{Binding Selpro,Mode=TwoWay}" SelectedValuePath="Id" DisplayMemberPath="Name"/>

效果演示

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#(WinForm) ComboBox和ListBox添加项及设置默认选择项

    Web控件DropDownList和WinForm控件ComboBox机制不一样. ComboBox没有对应的ListItem需要自己写一个: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WinListItem { /// <summary> /// 选择项类,用于ComboBox或者ListBox添加项 /// </summary>

  • C# 重写ComboBox实现下拉任意组件的方法

    一.需求 C#种的下拉框ComboBox不支持下拉复选框列表与下拉树形列表等,系统中需要用到的地方使用了第三方组件,现在需要将第三方组件替换掉. 二.设计 基本思路:重写ComboBox,将原生的下拉部分屏蔽,使用toolStripDropDown制作下拉弹出 三.问题解决 1. 问题:toolStripDropDown中放toolStripControlHost时会有边框产生,同时CheckedListBox的duck为full时底端会有很大空白 解决: toolStripControlHos

  • C# ComboBox的联动操作(三层架构)

    项目需求:根据年级下拉框的变化使得科目下拉框绑定次年级下对应有的值 我们用三层架构的模式来实现 1.我们想和数据库交互,我们首先得来先解决DAL数据库交互层 01.获得年级下拉框的数据 在GradeDAL类中 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient;

  • C#实现绑定Combobox的方法

    本文实例讲述了C#实现绑定Combobox的方法.分享给大家供大家参考.具体实现方法如下: public class StaticVariable { public Dictionary<string, string> tabTypeArray; public Dictionary<string, string> transTimeArray; public Dictionary<string, string> fileDealTypeArray; public Sta

  • C#实现ComboBox自动匹配字符

    1. 采用CustomSource当做提示集合 将下列代码添加到窗口加载函数中即可.假设unitNameList是获取的想要添加到下拉列表中的字符串列表. 复制代码 代码如下: AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); // 获取单位列表 List<string> unitNameList = this.getAllUnitName(); foreach (string unitn

  • jQuery EasyUI API 中文文档 - ComboBox组合框

    扩展自 $.fn.combo.defaults. 用 $.fn.combobox.defaults 重写了 defaults. 依赖 combo 用法 <select id="cc" name="dept" style="width:200px;"> <option value="aa">aitem1</option> <option>bitem2</option>

  • C#用ComboBox控件实现省与市的联动效果的方法

    本文实例讲述了C#用ComboBox控件实现省与市的联动效果的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: using System;  using System.Collections.Generic;  using System.ComponentModel;  using System.Data;  using System.Drawing;  using System.Linq;  using System.Text;  using System.Windows.

  • C# listview添加combobox到单元格的实现代码

    实现代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplicat

  • C#实现ComboBox控件显示出多个数据源属性的方法

    本文实例讲述了C#实现ComboBox控件显示出多个数据源属性的方法.分享给大家供大家参考.具体如下: public partial class Form4 : Form { private Bitmap myBitmap; public Form4() { InitializeComponent(); DataTable dt = new DataTable(); DataColumn dc1 = new DataColumn("Name", typeof(System.String

  • c#构造ColorComboBox(颜色下拉框)

    复制代码 代码如下: class ColorComboBox : ComboBox    {        /// <summary>        /// 当前选中色        /// </summary>        public Color SelectedColor        {            get { return Color.FromName(this.Text); }        }        /// <summary>     

随机推荐