我正在尝试移动物品以使用listview
在largeImage style.
内重新排序。问题存在于getItemAt(x, y)
内部的dragdrop
方法中,因为只有当dragDrop
没有完全在现有项目上执行时,此方法才会返回null(通常我在两个项目之间删除,它更直观imo)。
private void lvPictures_DragDrop(object sender, DragEventArgs e)
{
Point p = lvPictures.PointToClient(new Point(e.X, e.Y));
ListViewItem MovetoNewPosition = lvPictures.GetItemAt(p.X, p.Y);
//MovetoNewPosition is null
}
所以重点是,如果在两个项目之间执行dragDrop
,那么如何获得最接近的项目 - 而不是超过一个?
答案向我指出了正确的方向,这就是我如何实现“找到最近”的方法:(可能不完美,但它现在有效)
ListViewItem itemToBeMoved = (e.Data.GetData(typeof(ListView.SelectedListViewItemCollection)) as ListView.SelectedListViewItemCollection)[0];
ListViewItem itemToBeMovedClone = (ListViewItem)itemToBeMoved.Clone();
ListViewItem itemInDropPosition = listView.GetItemAt(p.X, p.Y);
if (itemInDropPosition == null)
{
ListViewItem leftItem = listView.FindNearestItem(SearchDirectionHint.Left, p);
ListViewItem rightItem = listView.FindNearestItem(SearchDirectionHint.Right, p);
if (leftItem == null && rightItem == null)
{
return;
}
else if (leftItem == null)
{
itemInDropPosition = rightItem;
}
else if (rightItem == null)
{
itemInDropPosition = leftItem;
}
else
{
//PGM: appens that if you move to the right or to the left, between two items, the left item (if moving to the right) or the right item (if moving to the left) is wrong, because it select not the first one, but the second
if (rightItem.Index - leftItem.Index > 1 && leftItem.Index < itemToBeMoved.Index && rightItem.Index <= itemToBeMoved.Index)
{
//we are moving to the left
rightItem = listView.Items[rightItem.Index - 1];
}
else if (rightItem.Index - leftItem.Index > 1 && leftItem.Index >= itemToBeMoved.Index && rightItem.Index > itemToBeMoved.Index)
{
//we are moving to the right
leftItem = listView.Items[leftItem.Index + 1];
}
else if (rightItem.Index - leftItem.Index > 1)
{
//significa che è stato spostato sul posto e non va mosso
return;
}
if (Math.Abs(p.X - leftItem.Position.X) < Math.Abs(p.X - rightItem.Position.X))
{
itemInDropPosition = leftItem;
}
else
{
itemInDropPosition = rightItem;
}
}
}
ListView.FindNearestItem会更好地完成你想要完成的任务吗?