WPF Listbox auto scroll while dragging(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列表框在拖动时自动滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:WPF列表框在拖动时自动滚动


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01