2

1) 如何使用 Drag&Drop 移动 ListView 中的项目?我已经为从目录中拖动的文件实现了 D&D 副本。

2) 顺便说一句,你如何通过 D&D 获取到 ListView 的目录链接,我见过通过 D&D 从 Windows 资源管理器的地址栏中获取目录路径的应用程序。

private void lvwFiles_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.None;
}

private void lvwFiles_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var paths = (string[])e.Data.GetData(DataFormats.FileDrop);
        var path = Path.GetDirectoryName(paths[0]);
        paths = Media.FilterPaths(paths);
        lvwFilesAdd(path, paths);
        lvwFilesWrite();
    }
}

找到这个@Microsoft(VS2005; http: //support.microsoft.com/kb/822483),我试图理解这段代码并让它在我的程序中工作。我将了解如何将其与 DragEnter 和 DragDrop 事件处理程序中已有的代码分开。

//lvwFiles_ItemDrag event handler
//
//Begins a drag-and-drop operation in the ListView control.
lvwFiles.DoDragDrop(lvwFiles.SelectedItems, DragDropEffects.Move);

//lvwFiles_DragEnter event handler
//
int len=e.Data.GetFormats().Length-1 ;
int i;
for (i = 0 ; i<=len ;i++)
{
    if (e.Data.GetFormats()[i].Equals("System.Windows.Forms.ListView+SelectedListViewItemCollection"))
    {
        //The data from the drag source is moved to the target. 
        e.Effect = DragDropEffects.Move;
    }
}

//lvwFiles_DragDrop event handler
//
//Return if the items are not selected in the ListView control.
if(lvwFiles.SelectedItems.Count==0)
{
   return;
}
//Returns the location of the mouse pointer in the ListView control.
Point cp = lvwFiles.PointToClient(new Point(e.X, e.Y));
//Obtain the item that is located at the specified location of the mouse pointer.
ListViewItem dragToItem = lvwFiles.GetItemAt(cp.X, cp.Y);
if(dragToItem==null)
{
    return;
} 
//Obtain the index of the item at the mouse pointer.
int dragIndex = dragToItem.Index;
ListViewItem[] sel=new ListViewItem [lvwFiles.SelectedItems.Count];
for(int i=0; i<=lvwFiles.SelectedItems.Count-1;i++)
{
    sel[i]=lvwFiles.SelectedItems[i];
}
for(int i=0; i<sel.GetLength(0);i++)
{ 
    //Obtain the ListViewItem to be dragged to the target location.
    ListViewItem dragItem = sel[i];
    int itemIndex = dragIndex;
    if(itemIndex==dragItem.Index)
    {
        return;
    }
    if(dragItem.Index<itemIndex)
        itemIndex++;
    else
        itemIndex=dragIndex+i;
   //Insert the item at the mouse pointer.
   ListViewItem insertItem = (ListViewItem)dragItem.Clone();
   lvwFiles.Items.Insert(itemIndex, insertItem);
   //Removes the item from the initial location while 
   //the item is moved to the new location.
   lvwFiles.Items.Remove(dragItem);
}
4

1 回答 1

3

看看ObjectListView - 一个围绕 .NET WinForms ListView 的开源包装器。

它支持通过拖动重新排列列表视图项目,以及更多。请参阅从拖放中取出拖拽

替代文字

于 2010-01-18T10:55:35.027 回答