C # Drag & Drop Перемещение элементов в текущем ListView

2

1) Как перемещать элементы в ListView с помощью Drag & Drop? Я реализовал копию 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);
}
  • 0
    Вы спрашиваете, «как мне реализовать D + D для просмотра списка», затем вы публикуете код. Это настоящий вопрос?
  • 0
    Код получает пути к файлам в каталоге, я спрашиваю о перемещении элементов в ListView из одной позиции в другую. Да, они связаны, но не совпадают.
Показать ещё 2 комментария
Теги:
drag-and-drop
listview
move

1 ответ

3
Лучший ответ

Посмотрите ObjectListView - оболочку с открытым исходным кодом вокруг .NETViewForms ListView.

Он поддерживает переупорядочивание элементов списка списка, перетаскивая их, а также намного больше. См. Выполнение перетаскивания из Drag and Drop

alt text http://objectlistview.sourceforge.net/cs/_images/dragdrop-dropbetween.png

  • 1
    Спасибо за ссылку. В источнике содержится более 20 файлов .cs, а в одной из них более 9000 строк, я хотел знать только, как это сделать, имея в виду, что я уже использую событие для чего-то другого, например файлов D & D из каталога. Я проверил свойства и метод, упомянутые в статье, но не получил его, это всего лишь одна команда в методе CanDrop: e.Effect = DragDropEffects.Move;
  • 0
    Это многое делает, вы правы. Перетаскивание по списку сильно отличается от приема капель из других приложений. Это на самом деле довольно сложно, если учесть автоматическую прокрутку и обратную связь с пользовательским интерфейсом. ObjectListView проделывает большую работу, чтобы другим программистам было легко его использовать.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню