UWP:对ListView中的项目重新排序时,请使用Move而不是Remove + Insert

时间:2019-11-06 21:36:27

标签: listview uwp

我正在使用绑定到ListViewObservableCollection控件。我已经设置了控件,以支持使用以下设置对集合中的项目进行重新排序:

<ListView
    AllowDrop="True"
    CanDragItems="True"
    CanReorderItems="True">
    ...
</ListView>

一切都很好,除了我注意到尽管源集合支持Move()方法,列表视图还是使用Remove()+ Insert()。

问题是,我还通过响应CollectionChanged事件在集合上实现了Undo-Redo功能。而且由于列表视图执行的是两个动作而不是一个动作,因此我需要执行两次“撤消”操作才能到达移动之前的状态。另一方面,如果我通过代码在集合上调用Move()方法,则只需要一个“撤消”操作即可。

所以我的问题是:如何强制列表视图使用Move()方法?

1 个答案:

答案 0 :(得分:4)

  

所以我的问题是:如何强制列表视图使用Move()方法?

当前的ListView不提供支持此操作的属性或方法。

ListView的数据源不一定是ObservableCollection,它可以是数组,列表或其他集合,并且这些集合可能没有Move()方法。

但是大多数集合都支持RemoveInsert方法。当ListView执行数据重新排序时,调用RemoveInsert方法是最佳选择。

Move的{​​{1}}方法也是基于此实现的。根据当前的开源 .Net Core ,我发现了ObservableCollection的{​​{3}}。

ObservableCollection.Move

这是.Net Framework的implementation。(几乎相同)

尽管UWP没有开源,但是没有根本的区别。

可以看出,即使/// <summary> /// Called by base class ObservableCollection&lt;T&gt; when an item is to be moved within the list; /// raises a CollectionChanged event to any listeners. /// </summary> protected virtual void MoveItem(int oldIndex, int newIndex) { CheckReentrancy(); T removedItem = this[oldIndex]; base.RemoveItem(oldIndex); base.InsertItem(newIndex, removedItem); OnIndexerPropertyChanged(); OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex); } 在内部也使用ObservableCollectionRemove方法,因此Insert并未刻意强调{{1}的使用}方法来调整元素在集合中的位置。

最诚挚的问候。