如何在同一ListView中拖放项目?

在此处输入图像描述

考虑这是一个显示文件和文件夹的ListView,我已经为复制/移动/重命名/显示属性等编写了代码,我只需要再做一件事了。 如何在Windows资源管理器中拖放相同的ListView,我有移动和复制function,我只需要获取用户在某个文件夹中丢弃的项目或以其他方式我需要获取这两个参数来调用复制function

void copy(ListViewItem [] droppedItems, string destination path) { // Copy target to destination } 

首先将列表视图的AllowDrop属性设置为true。 实现ItemDrag事件以检测拖动的开始。 我将使用私有变量来确保D + D仅在控件内部起作用:

  bool privateDrag; private void listView1_ItemDrag(object sender, ItemDragEventArgs e) { privateDrag = true; DoDragDrop(e.Item, DragDropEffects.Copy); privateDrag = false; } 

接下来你需要DragEnter事件,它会立即触发:

  private void listView1_DragEnter(object sender, DragEventArgs e) { if (privateDrag) e.Effect = e.AllowedEffect; } 

接下来,您将希望选择用户可以放置的项目。 这需要DragOver事件并检查正在hover的项目。 您需要将代表文件夹的项目与常规“文件”项目区分开来。 一种方法是使用ListViewItem.Tag属性。 例如,您可以将其设置为文件夹的路径。 使此代码有效:

  private void listView1_DragOver(object sender, DragEventArgs e) { var pos = listView1.PointToClient(new Point(eX, eY)); var hit = listView1.HitTest(pos); if (hit.Item != null && hit.Item.Tag != null) { var dragItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem)); copy(dragItem, (string)hit.Item.Tag); } } 

如果要支持拖动多个项目,请将拖动对象设为ListView.SelectedIndices属性。