Question

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>
Était-ce utile?

La solution 2

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 ListViews. 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.

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top