ListView拖放重新排序 - 向左拖动时不起作用

时间:2011-11-21 12:34:49

标签: c# winforms listview drag-and-drop

作为标题真的 - 我有一些代码用于在ListView('LargeIcon'视图格式)中重新排序一些缩略图,并且在向右拖动图像(即更大的索引)时效果很好。但是当向左拖动它根本不起作用。

有什么想法吗?

  private void lstImages_ItemDrag(object sender, ItemDragEventArgs e)
    {
        lstImages.DoDragDrop(lstImages.SelectedItems, DragDropEffects.Move);
    }

    private void lstImages_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection)))
        {
            e.Effect = DragDropEffects.Move;
        }
    }

    private void lstImages_DragDrop(object sender, DragEventArgs e)
    {
        if (lstImages.SelectedItems.Count == 0) return;

        Point p = lstImages.PointToClient(new Point(e.X, e.Y));
        ListViewItem dragToItem = lstImages.GetItemAt(p.X, p.Y);

        if (dragToItem == null) return;

        int dragIndex = dragToItem.Index;

        ListViewItem dataItem = (e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)) as ListView.SelectedListViewItemCollection)[0];
        int itemIndex = dragIndex;
        if (itemIndex == dataItem.Index) return;

        itemIndex = itemIndex + 1;

        ListViewItem insertItem = (ListViewItem)dataItem.Clone();
        lstImages.Items.Insert(itemIndex, insertItem);
        lstImages.Items.Remove(dataItem);
    }

1 个答案:

答案 0 :(得分:2)

我稍微修改了你的代码,现在可以了。 (只是_DragDrop部分)。似乎有一个错误,它可以通过在拖动和放大期间更改对齐来修复。下降。

  listView1.Alignment = ListViewAlignment.Default;
  if (listView1.SelectedItems.Count == 0)
    return;
  Point p = listView1.PointToClient(new Point(e.X, e.Y));
  ListViewItem MovetoNewPosition = listView1.GetItemAt(p.X, p.Y);
  if (MovetoNewPosition == null) return;
  ListViewItem DropToNewPosition = (e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)) as ListView.SelectedListViewItemCollection)[0];
  ListViewItem CloneToNew = (ListViewItem)DropToNewPosition.Clone();
  int index = MovetoNewPosition.Index;
  listView1.Items.Remove(DropToNewPosition);
  listView1.Items.Insert(index, CloneToNew);
  listView1.Alignment = ListViewAlignment.SnapToGrid;