WPF DataGrid绑定嵌套List<T>实现CUSTOMER_CODE过滤技术问询
按CUSTOMER_CODE过滤WPF DataGrid的实现方案
咱直接上实用的解决方案,结合WPF的ICollectionView来实现过滤是最靠谱的,既能保证UI自动响应过滤变化,还能完美适配你的RowDetails结构。
第一步:调整数据集合类型,引入集合视图
首先把你原来的List<CUSTCARDLevel>换成ObservableCollection<CUSTCARDLevel>(它会自动通知UI集合的增删改),然后用ICollectionView来包装这个集合——这货专门负责过滤、排序这类UI层面的数据操作。
在你的ViewModel里添加这些代码:
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Data; // 替换原List为ObservableCollection private ObservableCollection<CUSTCARDLevel> _customerCollection; public ObservableCollection<CUSTCARDLevel> CustomerCollection { get => _customerCollection; set { _customerCollection = value; OnPropertyChanged(nameof(CustomerCollection)); // 创建对应的集合视图 CustomerView = CollectionViewSource.GetDefaultView(_customerCollection); // 绑定过滤方法 CustomerView.Filter = FilterItemsByCustomerCode; } } // 这个视图就是要绑定到DataGrid的ItemsSource public ICollectionView CustomerView { get; private set; } // 绑定到过滤控件的文本属性,用来接收用户输入的过滤关键词 private string _filterCustomerCode; public string FilterCustomerCode { get => _filterCustomerCode; set { _filterCustomerCode = value; OnPropertyChanged(nameof(FilterCustomerCode)); // 每次输入变化时刷新过滤结果 CustomerView?.Refresh(); } }
第二步:实现过滤逻辑
写一个过滤方法,判断每条数据是否符合用户输入的CUSTOMER_CODE条件:
private bool FilterItemsByCustomerCode(object item) { if (item is not CUSTCARDLevel customerItem) return false; // 如果过滤框为空,直接显示所有数据 if (string.IsNullOrWhiteSpace(FilterCustomerCode)) return true; // 这里做模糊匹配,忽略大小写,你也可以改成精确匹配 return customerItem.CUSTOMER_CODE?.IndexOf(FilterCustomerCode, StringComparison.OrdinalIgnoreCase) >= 0; }
第三步:绑定XAML控件
把过滤控件(比如TextBox)和DataGrid都绑定到ViewModel的对应属性:
<!-- 过滤输入框 --> <TextBox Text="{Binding FilterCustomerCode, UpdateSourceTrigger=PropertyChanged}" Margin="10" PlaceholderText="输入客户代码进行过滤..."/> <!-- 主DataGrid --> <DataGrid ItemsSource="{Binding CustomerView}" AutoGenerateColumns="False" Margin="10"> <!-- 主列定义 --> <DataGrid.Columns> <DataGridTextColumn Header="客户代码" Binding="{Binding CUSTOMER_CODE}" Width="150"/> <!-- 其他业务列自己补充 --> </DataGrid.Columns> <!-- RowDetails部分,和你原来的绑定逻辑一致 --> <DataGrid.RowDetailsTemplate> <DataTemplate> <DataGrid ItemsSource="{Binding FSClist}" AutoGenerateColumns="True" Margin="20 5"/> </DataTemplate> </DataGrid.RowDetailsTemplate> </DataGrid>
额外优化建议
- 把
CUSTCARDLevel里的_fSClist换成ObservableCollection<FSCLevel>,这样RowDetails里的DataGrid也能自动响应子数据的变化; - 如果数据量很大,频繁刷新会导致UI卡顿,可以给
FilterCustomerCode的setter加个延迟触发(比如用DispatcherTimer延迟300ms再调用CustomerView.Refresh()); - 过滤逻辑可以根据需求调整,比如改成精确匹配
customerItem.CUSTOMER_CODE.Equals(FilterCustomerCode, StringComparison.OrdinalIgnoreCase)。
内容的提问来源于stack exchange,提问作者Heisenberg
相关产品推荐
相关产品推荐

