gpt4 book ai didi

c# - ListBox DragDrop 自动滚动问题?

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:08 25 4
gpt4 key购买 nike

我已经使用以下方法在列表框中成功实现了拖放:

Bea Stollnitz - 如何在数据绑定(bind)的 ItemsControl 之间拖放项目: http://www.zagstudio.com/blog/488#.U15ozvldU9Y

但是,当列表有一个滚动条并且我在列表的末尾时,当我拖动一个项目时,ListBox 不会自动滚动。
我如何融入这种行为?

编辑:当我越过列表的底部边框时,我希望它滚动以便我可以放在较低的项目上的某个地方?

最佳答案

我使用附加属性实现此目的,该属性添加了在拖动时鼠标向其顶部或底部移动时滚动控件的功能。这是附加的属性类:-

public class DragDropAttProps
{
public static readonly DependencyProperty ScrollOnDragDropProperty =
DependencyProperty.RegisterAttached(
"ScrollOnDragDrop",
typeof(bool),
typeof(DragDropAttProps),
new PropertyMetadata(false, HandleScrollOnDragDropChanged));

public static bool GetScrollOnDragDrop(DependencyObject element)
{
return (bool)element.GetValue(ScrollOnDragDropProperty);
}
public static void SetScrollOnDragDrop(DependencyObject element, bool value)
{
element.SetValue(ScrollOnDragDropProperty, value);
}

private static void HandleScrollOnDragDropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var container = d as FrameworkElement;
if (d == null)
{
Debug.Fail("Invalid type!");
}

Unsubscribe(container);

if (true.Equals(e.NewValue))
{
Subscribe(container);
}
}

private static void Subscribe(FrameworkElement container)
{
container.PreviewDragOver += OnContainerPreviewDragOver;
}

private static void Unsubscribe(FrameworkElement container)
{
container.PreviewDragOver -= OnContainerPreviewDragOver;
}

private static void OnContainerPreviewDragOver(object sender, DragEventArgs e)
{
const double Tolerance = 60;
const double Offset = 20;

var container = sender as FrameworkElement;
if (container == null)
{
return;
}

var scrollViewer = GetFirstVisualChild<ScrollViewer>(container);
if (scrollViewer == null)
{
return;
}

var verticalPos = e.GetPosition(container).Y;

if (verticalPos < Tolerance)
{
// Top of visible list? Scroll up.
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - Offset);
}
else if (verticalPos > container.ActualHeight - Tolerance)
{
// Bottom of visible list? Scroll down.
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset + Offset);
}
}

private static T GetFirstVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
if (child is T)
{
return (T)child;
}

var childItem = GetFirstVisualChild<T>(child);
if (childItem != null)
{
return childItem;
}
}
}

return null;
}
}

最后,在控件的 XAML 上指定附加属性。免责声明:我在 TreeView 上使用这种方法,但它应该适用于任何可滚动控件,例如列表框:-

<UserControl xmlns:attProps="clr-namespace:MyAssembly.AttachedProperties;assembly=MyAssembly">

<TreeView attProps:DragDropAttProps.ScrollOnDragDrop="True">

关于c# - ListBox DragDrop 自动滚动问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com