CollectionViewSource.Windows Store应用程序中的SortDescriptors
本文关键字:SortDescriptors 应用程序 Windows Store CollectionViewSource | 更新日期: 2023-09-27 18:14:50
在我的Windows Phone应用程序中,我使用CollectionViewSource.SortDescriptors
来排序我的LongListSelector
s内容。现在我迁移到Windows运行时应用程序,并使用ListView
来显示我的内容。(WinRT没有SortDescriptors
)
在我的ObserveableCollection
上使用OrderBy<>()
不是一个选项,因为我动态地添加了项目(这将导致ListView
的完全重新加载)。
如何在ObservableCollection
上"二进制插入"(类似于List<>
的可能性),或者是否有CollectionViewSource
的替代方案
您可以使用像这样的东西:带有过滤和排序的winRT CollectionView
或者你可以创建一个类并覆盖ObservableCollection。插入条目
public class SortedCollection<T> : ObservableCollection<T> where T : IComparable<T>
{
protected override void InsertItem(int index, T item)
{
int sortedIndex = FindSortedIndex(item);
base.InsertItem(sortedIndex, item);
}
private int FindSortedIndex(T item)
{
//simple sorting algorithm
for (int index = 0; index < this.Count; index++)
{
if (item.CompareTo(this[index]) > 0)
{
return index;
}
}
return 0;
}
}
要使用这个类创建一个新的集合并添加项目。
SortedCollection<int> sortedCollection = new SortedCollection<int>();
sortedCollection.Add(3);
sortedCollection.Add(1);
sortedCollection.Add(5);
sortedCollection.Add(4);
sortedCollection.Add(2);
//the sorted collection will be 1,2,3,4,5