Wpf ScrollViewer Scroll Amount

前端 未结 4 837
慢半拍i
慢半拍i 2021-02-05 08:03

Is it possible to change the amount that the WPF ScrollViewer scrolls? I am simply wondering if it\'s possible to change the scrollviewer so that when using the mouse wheel or t

4条回答
  •  遥遥无期
    2021-02-05 08:38

    You could implement a behavior on the scrollviewer. In my case CanContentScroll did not work. The solution below works for scrolling with the mouse wheel as well as draging the scrollbar.

    public class StepSizeBehavior : Behavior
    {
        public int StepSize { get; set; }
    
        #region Attach & Detach
        protected override void OnAttached()
        {
            CheckHeightModulesStepSize();
            AssociatedObject.ScrollChanged += AssociatedObject_ScrollChanged;
            base.OnAttached();
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.ScrollChanged -= AssociatedObject_ScrollChanged;
            base.OnDetaching();
        }
        #endregion
    
        [Conditional("DEBUG")]
        private void CheckHeightModulesStepSize()
        {
            var height = AssociatedObject.Height;
            var remainder = height%StepSize;
            if (remainder > 0)
            {
                throw new ArgumentException($"{nameof(StepSize)} should be set to a value by which the height van be divised without a remainder.");
            }
        }
    
        private void AssociatedObject_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            const double stepSize = 62;
            var scrollViewer = (ScrollViewer)sender;
            var steps = Math.Round(scrollViewer.VerticalOffset / stepSize, 0);
            var scrollPosition = steps * stepSize;
            if (scrollPosition >= scrollViewer.ScrollableHeight)
            {
                scrollViewer.ScrollToBottom();
                return;
            }
            scrollViewer.ScrollToVerticalOffset(scrollPosition);
        }
    }
    

    You would use it like this:

    
        
            
        
    

提交回复
热议问题