Wpf ScrollViewer滚动金额

Bra*_*onS 14 wpf scrollviewer

是否可以更改WPF ScrollViewer滚动的数量?我只是想知道是否可以更改滚动查看器,以便在使用鼠标滚轮或滚动查看器箭头时,可以更改增量滚动的数量.

Dre*_*rsh 14

简短的回答是:没有编写一些自定义滚动代码就没有办法做到这一点,但是不要让那吓到你并不是那么难.

ScrollViewer可以通过使用物理单位(即像素)滚动或通过与IScrollInfo实现交互来使用逻辑单元.这是通过设置CanContentScroll属性来控制的,其中值false表示"使用物理单位滚动内容",值true表示"逻辑滚动内容".

那么ScrollViewer如何在逻辑上滚动内容呢?通过与IScrollInfo实现进行通信.因此,当有人执行逻辑操作时,您可以准确地接管面板内容滚动的程度.查看IScrollInfo的文档以获取可以请求滚动的所有测量逻辑单元的列表,但是由于您提到了鼠标滚轮,因此您将最感兴趣的是MouseWheelUp/Down/Left/Right方法.


Gle*_*den 9

这是一个简单、完整且有效的WPF ScrollViewer类,它具有SpeedFactor用于调整鼠标滚轮灵敏度的数据绑定属性。设置SpeedFactor为 1.0 意味着与 WPF 相同的行为ScrollViewer。依赖属性的默认值是2.5,它允许非常快速的滚轮滚动。

当然,您也可以通过绑定到SpeedFactor属性本身来创建其他有用的功能,即,轻松地允许用户控制乘数。

public class WheelSpeedScrollViewer : ScrollViewer
{
    public static readonly DependencyProperty SpeedFactorProperty =
        DependencyProperty.Register(nameof(SpeedFactor),
                                    typeof(Double),
                                    typeof(WheelSpeedScrollViewer),
                                    new PropertyMetadata(2.5));

    public Double SpeedFactor
    {
        get { return (Double)GetValue(SpeedFactorProperty); }
        set { SetValue(SpeedFactorProperty, value); }
    }

    protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
    {
        if (!e.Handled && 
            ScrollInfo is ScrollContentPresenter scp &&
            ComputedVerticalScrollBarVisibility == Visibility.Visible)
        {
            scp.SetVerticalOffset(VerticalOffset - e.Delta * SpeedFactor);
            e.Handled = true;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

大约 3200 个数据项的“快速鼠标滚轮滚动”的完整 XAML 演示:

注意:'mscorlib' 引用仅用于访问演示数据。

<UserControl x:Class="RemoveDuplicateTextLines.FastScrollDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApp"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <local:WheelSpeedScrollViewer VerticalScrollBarVisibility="Auto">
        <ListBox ItemsSource="{Binding Source={x:Type sys:Object},Path=Assembly.DefinedTypes}" />
    </local:WheelSpeedScrollViewer>

</UserControl>
Run Code Online (Sandbox Code Playgroud)

快速鼠标滚轮:

在此处输入图片说明