wpf 中使用ScrollViewer 时鼠标滑轮按照内容进行滚动
xaml:
<ScrollViewer x:Name="sv" CanContentScroll="False" PreviewMouseWheel="ScrollViewer_PreviewMouseWheel" > </ScrollViewer>
后台:
private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { ScrollViewer viewer = sv; //sv 为Scrollview的名字,在Xaml文件中定义。 if (viewer == null) return; double num = Math.Abs((int)(e.Delta / 2)); double offset = 0.0; if (e.Delta > 0) { offset = Math.Max((double)0.0, (double)(viewer.VerticalOffset - num));//viewer.VerticalOffset获取包含滚动内容的垂直偏移量的值。 } else { offset = Math.Min(viewer.ScrollableHeight, viewer.VerticalOffset + num); } if (offset != viewer.VerticalOffset) { viewer.ScrollToVerticalOffset(offset);//将 ScrollViewer 内的内容滚动到指定的垂直偏移量位置。 e.Handled = true; } }