Reputation: 5538
I tried to reorder items in a ListView using drag and drop gestures.
In the "Drop" method I don't know how to get a reference to the "dropped" element, I only get reference to the "target drop" element.
See below:
private void Grid_Drop(object sender, DragEventArgs e)
{
ReorderItem draggedElement = (e.OriginalSource as Grid).DataContext as ReorderItem;
ReorderItem targetElement = ((Grid)sender).DataContext as ReorderItem;
Debug.WriteLine("Dragged element is:" + draggedElement.Index);
Debug.WriteLine("Drag target element is:" + targetElement.Index);
}
The reorder is between 0 and 1 indexes. The console index is both 1 :(
<ListView ItemsSource="{Binding Items}" CanReorderItems="True">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Background="{Binding Color}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AllowDrop="True"
Drop="Grid_Drop">
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
Upvotes: 3
Views: 13284
Reputation: 6375
Why re-invent the wheel when someone's done it already. Check out https://github.com/punker76/gong-wpf-dragdrop. Its available as a NuGet package as well.
although the documentation uses a ListBox
, I use it with a ListView
Upvotes: 6
Reputation: 5575
This is what DragEventArgs.Data
is for. Create a DataPackage
of the dragged item in the DragItemsStarting
event. The DataPackage
is passed between the two events.
Edit:
That enables dragging between two ListView
s. According to the documentation here:
"To enable users to reorder items using drag-and-drop interaction, you must set both the CanReorderItems
and AllowDrop
properties to true."
This should fix your issues.
Upvotes: 4