Gar*_*gin 2 wpf scroll drag-and-drop itemscontrol
我想在我的应用程序中实现拖动滚动功能,但在路上遇到了问题。有谁能够帮助我?我有一个 ScrollViewer,里面有一个 ItemsControl,在 ItemsTemplate 中我有一个 UserControl。我想将该 UserControl 拖动到 ItemsControl 中。当我拖动到 ItemsControl 的边界时,我希望 ScrollViewer 向下滚动。
protected override void OnPreviewMouseMove(System.Windows.Input.MouseEventArgs e)
{
if (this.IsMouseCaptured)
{
// Get the new mouse position.
Point mouseDragCurrentPoint = e.GetPosition(this);
if (Math.Abs(mouseDragCurrentPoint.Y - this.ActualHeight) <= 50)
{
this._scrollStartOffset.Y += 5;
_containingScrollViewer.ScrollToVerticalOffset(this._scrollStartOffset.Y);
}
if (mouseDragCurrentPoint.Y <= 50)
{
this._scrollStartOffset.Y -= 5;
_containingScrollViewer.ScrollToVerticalOffset(this._scrollStartOffset.Y);
}
}
base.OnPreviewMouseMove(e);
}
Run Code Online (Sandbox Code Playgroud)
当我通过调用DragDrop.DoDragDrop()滚动开始拖动时不会发生。但是当我禁用拖动时,ScrollViewer 会根据鼠标位置向下滚动。也许在拖动和捕获鼠标时我没有考虑到一些事情?谢谢关注。加雷金
小智 5
使用 DragDrop.DoDragDrop() 时,我使用了一个处理 Me.DragOver 事件的 Sub(在 VB 中),因此它看起来如下所示。请注意,我的控件有一个包含在 ScrollViewer 中的 ListBox。
Private Sub ListBox_Items_DragOver(ByVal sender As System.Object, ByVal e As System.Windows.DragEventArgs) Handles Me.DragOver
Dim currentMousePoint As Point = e.GetPosition(_containtingScrollViewer)
If Math.Abs(currentMousePoint.Y - _containtingScrollViewer.ActualHeight) <= 50 Then
_containtingScrollViewer.ScrollToVerticalOffset(currentMousePoint.Y + 5)
End If
If currentMousePoint.Y <= 50 Then
_containtingScrollViewer.ScrollToVerticalOffset(currentMousePoint.Y - 5)
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
这使我能够在拖动项目时滚动。您可以根据需要调整容差以获得更好/更平滑的滚动。