Dot-Net

是什麼導致 WPF ListCollectionView 使用自定義排序來重新排序其項目?

  • January 10, 2020

考慮此程式碼(出於範例目的而通用的類型名稱):

// 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));

使用 .NET 4.5,WPF 添加了實時整形: https ://docs.microsoft.com/en-us/dotnet/framework/wpf/getting-started/whats-new#repositioning-data-as-the-datas-values-改變生活塑造

這允許您設置用於排序/分組/過濾的屬性,並且如果屬性值更改,則再次對項目進行排序/分組/過濾。在你的情況下:

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

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

// Add sorting
_itemsView = CollectionViewSource.GetDefaultView(_items)
_itemsView.SortDescriptions.Add(new SortDescription("PropertyName", ListSortDirection.Ascending));

// Enable live sorting
// Note that if you don't add any LiveSortingProperties, it will use SortDescriptions
((ICollectionViewLiveShaping)_itemsView).LiveSortingProperties.Add("PropertyName");
((ICollectionViewLiveShaping)_itemsView).IsLiveSorting = true;

正如接受的答案指示我的那樣,我可以使用程式碼強制單個項目重新定位

IEditableCollectionView collectionView = DataGrid.Items;

collectionView.EditItem(changedItem);
collectionView.CommitEdit();

視圖模型(集合中的項目)changedItem在哪裡。ItemsSource

這樣,您就不需要您的項目來實現任何介面,例如IEditableObject(在我看來,在某些情況下,合約非常複雜且難以實現)。

引用自:https://stackoverflow.com/questions/601864