Drag and drop item in same ListView

2019-07-17 10:53发布

I have following ListView

<ListView Name="listAccounts" Width="300" AllowDrop="True" SelectionMode="Single" CanDragItems="True" CanDrag="True" CanReorderItems="True" Background="{ThemeResource myBackground}" DragItemsStarting="listAccounts_DragItemsStarting" Drop="listAccounts_Drop">

and defined my event handlers as

private void listAccounts_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
    e.Data.SetData("itemIndex", (e.Items[0] as AccountList).Text.ToString());
}

private async void listAccounts_Drop(object sender, DragEventArgs e)
{
    string itemIndexString = await e.Data.GetView().GetTextAsync("itemIndex");
}

I don't know what else I can do. I want to realize the movement of the list items in the same list.

1条回答
祖国的老花朵
2楼-- · 2019-07-17 11:13

I went over to the official Windows 10 samples, looked for the drag-drop sample and trimmed it down (like removing the drag from target to source). Turns out you don't even have to handle any events to make re-ordering in a single ListView work.

<ListView x:Name="TargetListView"
                Grid.Row="2" Grid.Column="1" Margin="8,4"
                CanReorderItems="True" CanDrag="True" AllowDrop="True"
                />

Check your ObservableCollection after reordering items and you'll notice it's correct. If you want to track the re-ordering, you'll have to check the CollectionChanged event on your ObservableCollection, as there is no event on the ListView to do this.

If you want to support drag & drop accross multilple listviews, I'd say have another look at the sample.

查看更多
登录 后发表回答