How to drag & drop items in the same ListView?

只愿长相守 提交于 2019-12-08 01:16:40

问题


Consider this is a ListView that shows files and folders, I have already wrote code for copy/move/rename/show properties ...etc and I just need one more last thing. how to drag and drop in the same ListView like in Windows Explorer, I have move and copy functions, and I just need to get the items which user drops in some folder or in other way I need to get these two parameters to call copy function

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

回答1:


Start by setting the list view's AllowDrop property to true. Implementing the ItemDrag event to detect the start of a drag. I'll use a private variable to ensure that D+D only works inside of the control:

    bool privateDrag;

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

Next you'll need the DragEnter event, it will fire immediately:

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

Next you'll want to be selective about what item the user can drop on. That requires the DragOver event and checking which item is being hovered. You'll need to distinguish items that represent a folder from regular 'file' items. One way you can do so is by using the ListViewItem.Tag property. You could for example set it to the path of the folder. Making this code work:

    private void listView1_DragOver(object sender, DragEventArgs e) {
        var pos = listView1.PointToClient(new Point(e.X, e.Y));
        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);
        }
    }

If you want to support dragging multiple items then make your drag object the ListView.SelectedIndices property.



来源:https://stackoverflow.com/questions/9443695/how-to-drag-drop-items-in-the-same-listview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!