CollectionViewSource的作用

之前在阅读Silverlight实例时,发现CollectionViewSource标签,不明白是什么作用。看了以下介绍,部分了然:[url]http://www.cnblogs.com/nankezhishi/archive/2010/01/26/bindingcollectionviewsource.html[/url]
public static class ComboBoxHelper { // 防抖计时器字典(按控件实例存储) private static readonly Dictionary<ComboBox, DispatcherTimer> _debounceTimers = new(); /// <summary> /// 带防抖的通用初始化方法 /// </summary> public static void InitializeFilterComboBox(ComboBox comboBox, int debounceTime = 300) { comboBox.ApplyTemplate(); var textBox = comboBox.Template.FindName("PART_EditableTextBox", comboBox) as TextBox; if (textBox == null) return; textBox.TextChanged += (s, e) => { // 防抖核心逻辑 if (_debounceTimers.TryGetValue(comboBox, out var timer)) { timer.Stop(); } else { timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(debounceTime) }; _debounceTimers[comboBox] = timer; } timer.Tick += (_, _) => { FilterItems(comboBox, textBox.Text); timer.Stop(); }; timer.Start(); }; } /// <summary> /// 通用过滤方法 /// </summary> /// <param name="comboBox"></param> /// <param name="input"></param> private static void FilterItems(ComboBox comboBox, string input) { try { if (comboBox.ItemsSource != null) { var view = CollectionViewSource.GetDefaultView(comboBox.ItemsSource); view.Filter = item => { // 双重空值检查 if (item == null || input == null) return false; // 安全类型转换 string itemStr = item as string ?? string.Empty; return itemStr.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0; }; } } catch (Exception ex) { Logs.WriteAbnormalLOG(54 + ex.Message); } } /// <summary> /// 带防抖的扩展方法 /// </summary> public static void EnableSearchFilter(this ComboBox comboBox, int debounceTime = 300) { try { comboBox.ApplyTemplate(); var textBox = comboBox.Template.FindName("PART_EditableTextBox", comboBox) as TextBox; if (textBox == null) return; var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(debounceTime) }; timer.Tick += (s, e) => { var currentText = textBox.Text; var view = CollectionViewSource.GetDefaultView(comboBox.ItemsSource); view.Filter = item => (item?.ToString() ?? "").Contains(currentText, StringComparison.OrdinalIgnoreCase); timer.Stop(); }; textBox.TextChanged += (s, e) => { timer.Stop(); timer.Start(); }; } catch (Exception ex) { Logs.WriteAbnormalLOG(84 + ex.Message); } } }这是过滤方法,以下是启动 dictionary_ShopID = new Dictionary<string, string>(); dictionary_ShopID["yi"] = "01"; dictionary_ShopID["er"] = "02"; dictionary_ShopID["san"] = "03"; // 打印字典 List<string> items = new List<string>(); foreach (var dic in dictionary_ShopID) { items.Add(dic.Key); } // 绑定数据并创建 CollectionView myComboBox1.ItemsSource = CollectionViewSource.GetDefaultView(items); myComboBox1.EnableSearchFilter();
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值