C#在ListView中实现拖拽时自动滚动&掉落 [英] C# Implementing Auto-Scroll in a ListView while Drag & Dropping

查看:13
本文介绍了C#在ListView中实现拖拽时自动滚动&掉落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Winforms ListView 中实现自动滚动(例如,当您靠近顶部或底部时,ListView 会滚动)?我在谷歌上四处搜寻,运气不佳.我不敢相信这不是开箱即用的!提前致谢戴夫

How do I implement Auto-Scrolling (e.g. the ListView scrolls when you near the top or bottom) in a Winforms ListView? I've hunted around on google with little luck. I can't believe this doesn't work out of the box! Thanks in advance Dave

推荐答案

滚动可以通过 ListViewItem.EnsureVisible 方法.您需要确定您当前拖过的项目是否位于列表视图的可见边界,并且不是第一个/最后一个.

Scrolling can be accomplished with the ListViewItem.EnsureVisible method. You need to determine if the item you are currently dragging over is at the visible boundary of the list view and is not the first/last.

private static void RevealMoreItems(object sender, DragEventArgs e)
{
    var listView = (ListView)sender;

    var point = listView.PointToClient(new Point(e.X, e.Y));
    var item = listView.GetItemAt(point.X, point.Y);
    if (item == null)
        return;

    var index = item.Index;
    var maxIndex = listView.Items.Count;
    var scrollZoneHeight = listView.Font.Height;

    if (index > 0 && point.Y < scrollZoneHeight)
    {
        listView.Items[index - 1].EnsureVisible();
    }
    else if (index < maxIndex && point.Y > listView.Height - scrollZoneHeight)
    {
        listView.Items[index + 1].EnsureVisible();
    }
}

然后将此方法连接到 DragOver 事件.

Then wire this method to the DragOver event.

targetListView.DragOver += RevealMoreItems;

targetListView.DragOver += (sender, e) =>
{
    e.Effect = DragDropEffects.Move;
};

这篇关于C#在ListView中实现拖拽时自动滚动&amp;掉落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆