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

本文关键字:拖放 不起作用 排序 新排序 ListView | 更新日期: 2023-09-27 18:15:14

作为标题真的-我有一些代码重新排序一些缩略图在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);
    }

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

我稍微修改了一下你的代码,现在它可以工作了。(只是_DragDrop部分)。似乎有一个bug,它可以通过改变拖动过程中的对齐来修复。下降。

  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;