WPF中CollectionView添加SortDescription报NotSupportedException问题
问题根因
你遇到的异常和EF Core、模型类定义没有直接关联,核心是用错了集合视图的类型:
- 你手动实例化的
CollectionView是WPF集合视图的基类,仅实现了最基础的集合遍历能力,本身不支持排序、筛选、分组功能。它的SortDescriptions属性返回的是一个静态的只读空集合(就是堆栈里提到的EmptySortDescriptionCollection),这个类没有实现插入、删除逻辑,任何向其中添加排序规则的操作都会直接抛出NotSupportedException。 - WPF中针对支持排序的列表数据源(比如
ObservableCollection),实际提供的是派生类ListCollectionView,只有这个类的SortDescriptions集合是可读写、支持增删排序规则的。
修正代码
两种可行的实现方式,二选一即可:
方式1:直接实例化支持排序的ListCollectionView
Database.Context Context = new Database.Context(); // 替换基类CollectionView为ListCollectionView ListCollectionView CV = new ListCollectionView(Context.BindDesign.Local.ToObservableCollection()); BindDesignIC.ItemsSource = CV; // 用nameof代替硬编码字符串,避免属性名变更后排序失效 CV.SortDescriptions.Add(new SortDescription(nameof(BindDesignModel.IsBinded), ListSortDirection.Ascending));
方式2:获取WPF自动生成的默认集合视图
WPF在你给ItemsControl绑定数据源时,会自动为数据源生成匹配的、支持对应功能的默认视图,不需要手动new视图对象:
Database.Context Context = new Database.Context(); var sourceCollection = Context.BindDesign.Local.ToObservableCollection(); BindDesignIC.ItemsSource = sourceCollection; // 获取数据源对应的默认视图,ObservableCollection的默认视图就是ListCollectionView类型 var CV = (ListCollectionView)CollectionViewSource.GetDefaultView(sourceCollection); CV.SortDescriptions.Add(new SortDescription(nameof(BindDesignModel.IsBinded), ListSortDirection.Ascending));
额外注意事项
你当前的模型类还有一个会导致排序不自动更新的隐患:IsBinded是依赖code值计算的属性,但你在code的setter里只触发了code自身的属性变更通知,没有通知IsBinded的变化。后续运行中修改code值时,UI不会感知到IsBinded的变更,排序结果也不会自动刷新,需要给code的setter补一行通知:
public string code { get => _code; set { _code = value; OnPropertyChanged(); // 补充IsBinded的变更通知 OnPropertyChanged(nameof(IsBinded)); } }
内容的提问来源于stack exchange,提问作者Melon NG
相关产品推荐
相关产品推荐

