Listview getItemAt返回null

时间:2018-11-02 00:08:00

标签: c# winforms

我正在尝试移动项目以将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;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

ListView.FindNearestItem在您要完成的工作上会更好吗?