UWP/C#:可观察的就地收集排序(不带滚动)
在UWP应用程序中,我试图对绑定到UWP/C#:可观察的就地收集排序(不带滚动),c#,sorting,uwp,observablecollection,C#,Sorting,Uwp,Observablecollection,在UWP应用程序中,我试图对绑定到列表视图的ObservableCollection进行排序-因此集合。OrderBy(..)(创建新集合)不是选项 到目前为止,我一直使用这种扩展方法: public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector) { List<TSource&
列表视图的ObservableCollection
进行排序-因此集合。OrderBy(..)
(创建新集合)不是选项
到目前为止,我一直使用这种扩展方法:
public static void Sort<TSource, TKey>(this
ObservableCollection<TSource> source, Func<TSource, TKey> keySelector)
{
List<TSource> sortedList = source.OrderBy(keySelector).ToList();
source.Clear();
foreach (var sortedItem in sortedList)
{
source.Add(sortedItem);
}
}
公共静态无效排序(此
ObservableCollection源,Func键选择器)
{
List sortedList=source.OrderBy(keySelector.ToList();
source.Clear();
foreach(分拣列表中的var分拣数据项)
{
来源.添加(sortedItem);
}
}
不幸的是,由于source.Clear()
和相应的ListView
滚动到顶部,当前的“滚动偏移量”被重置,这是非常糟糕的用户体验
有什么想法吗?我刚才在处理同一个问题,结果是:
Func<TempoMarking, IComparable> selectorGetter = null;
// Setting the selectorGetter here
for (int i = 0; i < Collection.Count; i++)
{
for (int j = 0; j < Collection.Count - 1; j++)
{
YourType currentItem = Collection[j];
if (selectorGetter(currentItem).CompareTo(selectorGetter(Collection[j + 1])) == 1)
{
Collection.Remove(currentItem);
Collection.Insert(j + 1, currentItem);
}
}
}
您可以尝试创建一个临时集合,其中包含原始集合中的所有项目,对其进行排序,然后循环遍历其项目,只对需要更新位置的项目重新排序。像这样的-
public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector)
{
var sortedSource = source.OrderBy(keySelector).ToList();
for (var i = 0; i < sortedSource.Count; i++)
{
var itemToSort = sortedSource[i];
// If the item is already at the right position, leave it and continue.
if (source.IndexOf(itemToSort) == i)
{
continue;
}
source.Remove(itemToSort);
source.Insert(i, itemToSort);
}
}
我发现这个与用户体验相关的问题非常有趣,我甚至为此做了一点准备下面的gif演示了最终结果。对我来说,它提供了一个更好的体验,因为我从视觉上知道,哪些项目是或不是通过排序重新定位的
我不熟悉您的问题,我是否应该问您,是否有人试图在source.Clear()之前的对象中保存“滚动偏移量”,并再次重置该值,这可能会有所帮助。这将是我的“最后手段”。这可能会起作用,但使用source.Clear()时,列表将首先滚动到顶部,然后在不久后重置为存储的“滚动偏移量”。这看起来很奇怪。您可以调用由可观察对象公开的。Move
,而不是source.Remove和Insert。不过,它在内部也是这样做的。需要记住的一点是,调用Move将触发集合更改事件,这些事件可能受欢迎,也可能不受欢迎。
public static void Sort<TSource, TKey>(this ObservableCollection<TSource> source, Func<TSource, TKey> keySelector)
{
var sortedSource = source.OrderBy(keySelector).ToList();
for (var i = 0; i < sortedSource.Count; i++)
{
var itemToSort = sortedSource[i];
// If the item is already at the right position, leave it and continue.
if (source.IndexOf(itemToSort) == i)
{
continue;
}
source.Remove(itemToSort);
source.Insert(i, itemToSort);
}
}
<ItemsPanelTemplate>
<ItemsStackPanel ItemsUpdatingScrollMode="KeepScrollOffset" />
</ItemsPanelTemplate>