gpt4 book ai didi

.net - 是什么导致 WPF ListCollectionView 使用自定义排序来重新排序其项目?

转载 作者:行者123 更新时间:2023-12-02 09:43:58 25 4
gpt4 key购买 nike

考虑以下代码(出于示例目的而通用类型名称):

// Bound to ListBox.ItemsSource
_items = new ObservableCollection<Item>();

// ...Items are added here ...

// Specify custom IComparer for this collection view
_itemsView = CollectionViewSource.GetDefaultView(_items)
((ListCollectionView)_itemsView).CustomSort = new ItemComparer();

当我设置 CustomSort 时,集合会按照我的预期进行排序。

但是,我要求数据在运行时重新排序,以响应 Item 属性的更改。 Item 类派生自 INotifyPropertyChanged,我知道当我的数据模板更新屏幕上的值时,该属性会正确触发,只是不会调用排序逻辑。

我还尝试引发 INotifyPropertyChanged.PropertyChanged 传递空字符串,以查看通用通知是否会导致启动排序。没有香蕉。

编辑为了回应肯特的建议,我想我应该指出,使用它对项目进行排序具有相同的结果,即集合排序一次,但随着数据变化重新排序:

_itemsView.SortDescriptions.Add(
new SortDescription("PropertyName", ListSortDirection.Ascending));

最佳答案

我找到了this article by Dr. WPF首先回答我的问题,然后继续讨论调用 Refresh 对性能的影响。一些关键摘录:

Unfortunately, the Refresh() method results in a complete regeneration of the view. When a Refresh() occurs within the view, it raises a CollectionChanged notification and supplies the Action as "Reset". The ItemContainerGenerator for the ListBox receives this notification and responds by discarding all the existing visuals for the items. It then completely regenerates new item containers and visuals.

然后,他描述了一种可以提高性能的巧妙解决方法。而不是调用刷新、删除、更改然后重新添加项目。

我本以为 ListView 可以跟踪更改的项目并知道在 View 中单独重新定位该项目。

.NET 3.5 SP1 中引入了一种新方法涉及接口(interface) IEditableObject,该接口(interface)通过使用 BeginEdit()CancelEdit()EndEdit 方法将数据绑定(bind)到模板来提供事务编辑()。阅读 the article了解更多信息。

编辑user346528 points out , IEditableObject 实际上并不是 3.5SP1 中的新内容。它实际上看起来已经在框架中 since 1.0 .

关于.net - 是什么导致 WPF ListCollectionView 使用自定义排序来重新排序其项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/601864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com