问题
I can't seem to figure this one out by reading the documentation for ObservableCollection.Move(int oldIndex, int newIndex) on MSDN:
oldIndex Type: System.Int32 The zero-based index specifying the location of the item to be moved. newIndex Type: System.Int32 The zero-based index specifying the new location of the item.
I don't understand how it works. What happens to the item with newIndex? My assumption is that the index of each item with index >= newIndex is decremented. Is that assumption correct? And more importantly, is that behavior explained or described somewhere on MSDN?
回答1:
Let me explain the behavior of Move in a form of a unit test:
[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);
}
回答2:
I would go for the simple explanation:
The object is moved to the position indicated, and then all objects in collection are re-indexed from zero and up.
回答3:
Apart from great answer of @nemesv what helps me to remember the behavior is that myObservableCollection.Move(oldIndex, newIndex) is equivalent of:
var movedItem = myObservableCollection[oldIndex];
myObservableCollection.RemoveAt(oldIndex);
myObservableCollection.Insert(newIndex, movedItem);
来源:https://stackoverflow.com/questions/10471222/how-does-observablecollectiont-moveint-int-work