Modifying an ObservableCollection using move() ?

Posted by user1202434 on Stack Overflow See other posts from Stack Overflow or by user1202434
Published on 2012-06-07T22:15:41Z Indexed on 2012/06/07 22:40 UTC
Read the original article Hit count: 93

Filed under:
|

I have a question relating to modifying the individual items in an ObservableCollection that is bound to a ListBox in the UI.

The user in the UI can multiselect items and then drop them at a particular index to re-order them.

So, if I have items {0,1,2,3,4,5,6,7,8,9} the user can choose items 2, 5, 7 (in that order) and choose to drop them at index 3, so that the collection now becomes,

{0,1,3, 2, 5, 7, 4, 8,9}

The way I have it working now, is like this inside of ondrop() method on my control, I do something like:

foreach (Item item in draggedItems)
{

   int oldIndex = collection.IndexOf(item.DataContext as MyItemType);
   int newIndex = toDropIndex;

  if (newIndex == collection.Count)
  {
         newIndex--;
  }


  if (oldIndex != newIndex)
  {
     collection.Move(oldIndex, newIndex);

  }

}

But the problem is, if I drop the items before the index where i start dragging my first item, the order becomes reversed...so the collection becomes,

{0,1,3, 7, 5, 2, 4, 8,9}

It works fine if I drop after index 3, but if i drop it before 3 then the order becomes reversed.

Now, I can do a simple remove and then insert all items at the index I want to, but "move" for me has the advantage of keeping the selection in the ui (remove basically de-selects the items in the list..)....so I will need to make use of the move method,

what is wrong with my method above and how to fix it? Thanks!

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf