wpf 使用拖放重新排列 ListView 中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22409416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reorder items in ListView using drag and drop
提问by Alexandru Circus
I tried to reorder items in a ListView using drag and drop gestures.
我尝试使用拖放手势对 ListView 中的项目重新排序。
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.
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 :(
重新排序介于 0 和 1 索引之间。控制台索引都是 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>
回答by Zeus82
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.
既然有人已经完成了,为什么还要重新发明轮子。查看 https://github.com/punker76/gong-wpf-dragdrop。它也可以作为 NuGet 包使用。
although the documentation uses a ListBox, I use it with a ListView
尽管文档使用了ListBox,但我将它与ListView
回答by Nate Diamond
This is what DragEventArgs.Datais for. Create a DataPackageof the dragged item in the DragItemsStartingevent. The DataPackageis passed between the two events.
这DragEventArgs.Data就是为了。DataPackage在DragItemsStarting事件中创建一个被拖动的项目。将DataPackage在两个事件之间传递。
Edit:
编辑:
That enables dragging between two ListViews. According to the documentation here:
这可以在两个ListViews之间拖动。根据此处的文档:
"To enable users to reorder items using drag-and-drop interaction, you must set both the CanReorderItemsand AllowDropproperties to true."
“要使用户能够使用拖放交互重新排序项目,您必须将CanReorderItems和AllowDrop属性都设置为 true。”
This should fix your issues.
这应该可以解决您的问题。

