I'm a long time WPF user but new to WinRT. I'm wondering if there's a built in way or easy way to integrate swapping functionality in containers so that a swap exchanges two items in the container. The behavior desired is drag an item and drop it on another item and have both the dragged item and the item it's dragged onto get their positions in the container swapped).
Example I have a list with 1 2 3 4 5 6 7 8, if I drag 7 "on" 4 I want the two items swapped so that the resulting list becomes 1 2 3 7 5 6 4 8
I'm currently using a GridView
with an ItemsWrapGrid
as it's container to display a lot of picture thumbnails. I need to be able to reorder them with the most commonly required action being a swap in the positions of two images.
Or if there's no built in way, can you hint me at what the "proper" direction to start doing it from scratch would be in WinRT? I'm thinking handle the drag and drop not at the container but at the item level, and manually swap the items in the ObservableCollection
?
The easiest way is to leverage
ObservableCollection
, and let theListBox
or w/e control take care of the rest.All you have to do is, basically, create drag & drop handler, figure out which item client wanted to move where(keep track of oldIndex / newIndex), and implement the swap:
ObservableCollection
will raise ´Replaced` action, WPF knows how to take care of.Here's something to get you going: http://www.hardcodet.net/2009/03/moving-data-grid-rows-using-drag-and-drop
You'd basically want to wrap it into attached behavior, and implement the swap in
ViewModel
.Both existing answers will do the swapping for you, at the data level. Here's what can be done to make the UI more user-friendly.
IMHO, the best UX to handle the swapping is, when you drag an item and move it over another, the latter should appear to where the dragged item was originally at. This clearly tells the user where exactly the items will go. Just like what's shown on the gif image below.
To do this you will need to create an
Image
and useRenderTargetBitmap
to copy the look of the drop item to its source, when the drag item moves over the drop item. Of course when the drag action starts, you need to get the position of the drag item so you know where exactly to put this image.Then, once the item is dropped, you should clear and hide the image and do the data exchange.
I have included a small sample project here just so you can check out how the animations are done. Please note that the data swapping part is not included, as I said, the other answers already explain it very well. :)
Here's how I did it (with thanks to this blog):
XAML code:
C# code: