我似乎无法通过阅读documentation for ObservableCollection.Move(int oldIndex, int newIndex) on MSDN来了解这一点:
oldIndex类型:System.Int32指定的从零开始的索引 要移动的项目的位置。 newIndex类型:System.Int32 从零开始的索引,指定项目的新位置。
我不明白它是如何运作的。 newIndex
项目会发生什么变化?我的假设是每个项目index >= newIndex
的索引递减。这个假设是否正确?更重要的是,在MSDN上某处解释或描述了这种行为吗?
答案 0 :(得分:30)
让我以单元测试的形式解释Move
的行为:
[Test]
public void ObservableTest()
{
var observable = new ObservableCollection<string> { "A", "B", "C", "D", "E" };
observable.Move(1, 3); // oldIndex < newIndex
// Move "B" to "D"'s place: "C" and "D" are shifted left
CollectionAssert.AreEqual(new[] { "A", "C", "D", "B", "E" }, observable);
observable.Move(3, 1); // oldIndex > newIndex
// Move "B" to "C"'s place: "C" and "D" are shifted right
CollectionAssert.AreEqual(new[] { "A", "B", "C", "D", "E" }, observable);
observable.Move(1, 1); // oldIndex = newIndex
// Move "B" to "B"'s place: "nothing" happens
CollectionAssert.AreEqual(new[] { "A", "B", "C", "D", "E" }, observable);
}
答案 1 :(得分:3)
我会选择简单的解释:
将对象移动到指示的位置,然后将集合中的所有对象从零开始重新编制索引。
答案 2 :(得分:0)