WPF列表框在拖动时自动滚动 [英] WPF Listbox auto scroll while dragging

查看:15
本文介绍了WPF列表框在拖动时自动滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 ListBox 的 WPF 应用程序.拖动机制已经实现,但是当列表太长并且我想将项目移动到不可见的位置时,我不能.

I have a WPF app that has a ListBox. The drag mechanism is already implemented, but when the list is too long and I want to move an item to a position not visible I can't.

例如,屏幕显示 10 个项目.我有20个项目.如果我想将最后一个项目拖到第一个位置,我必须拖到顶部并放下.向上滚动并再次拖动.

For example, the screen shows 10 items. And I have 20 items. If I want to drag the last item to the first position I must drag to the top and drop. Scroll up and drag again.

如何使 ListBox 自动滚动?

推荐答案

知道了.使用了ListBox的事件DragOver,使用了找到的函数here 获取列表框的 scrollviewer ,然后只需稍微调整一下 Position.

Got it. Used the event DragOver of the ListBox, used the function found here to get the scrollviewer of the listbox and after that its just a bit of juggling with the Position.

private void ItemsList_DragOver(object sender, System.Windows.DragEventArgs e)
{
    ListBox li = sender as ListBox;
    ScrollViewer sv = FindVisualChild<ScrollViewer>(ItemsList);

    double tolerance = 10;
    double verticalPos = e.GetPosition(li).Y;
    double offset = 3;

    if (verticalPos < tolerance) // Top of visible list?
    {
        sv.ScrollToVerticalOffset(sv.VerticalOffset - offset); //Scroll up.
    }
    else if (verticalPos > li.ActualHeight - tolerance) //Bottom of visible list?
    {
        sv.ScrollToVerticalOffset(sv.VerticalOffset + offset); //Scroll down.    
    }
}

public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
    // Search immediate children first (breadth-first)
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);

        if (child != null && child is childItem)
            return (childItem)child;

        else
        {
            childItem childOfChild = FindVisualChild<childItem>(child);

            if (childOfChild != null)
                return childOfChild;
        }
    }

    return null;
}

这篇关于WPF列表框在拖动时自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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