效果
xaml
<ScrollViewer x:Name="scrollViewer" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled" Background="#FFF1ADAD"PreviewMouseDown="ScrollViewer_OnPreviewMouseDown"PreviewMouseMove="ScrollViewer_OnPreviewMouseMove"PreviewMouseUp="ScrollViewer_OnPreviewMouseUp" ><StackPanel x:Name="stackPanel" Orientation="Horizontal" HorizontalAlignment="Left"><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick" /><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/><Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/></StackPanel></ScrollViewer>
代码
Point initialMousePoint = new();double horizontalOffset = 1;bool isMouseDown = false;private double mouseDist = 0;private void ScrollViewer_OnPreviewMouseDown(object sender, MouseButtonEventArgs e) { initialMousePoint = e.GetPosition(scrollViewer);horizontalOffset = scrollViewer.HorizontalOffset;isMouseDown = true;e.Handled = false;}private void ScrollViewer_OnPreviewMouseMove(object sender, MouseEventArgs e) {if (isMouseDown && e.LeftButton == MouseButtonState.Pressed) { scrollViewer.ScrollToHorizontalOffset(horizontalOffset + (initialMousePoint.X - e.GetPosition(scrollViewer).X)); }e.Handled = false;}private void ScrollViewer_OnPreviewMouseUp(object sender, MouseButtonEventArgs e) {isMouseDown = false;e.Handled = false; mouseDist = (e.GetPosition(scrollViewer) - initialMousePoint).Length; }private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { if (mouseDist < 1) { if (sender is Button btn) {btn.Content = DateTime.Now.Millisecond.ToString();}}}