当前位置:   article > 正文

WPF 鼠标拖拽平移

WPF 鼠标拖拽平移

 

效果

xaml

  1. <ScrollViewer x:Name="scrollViewer" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Disabled" Background="#FFF1ADAD"
  2. PreviewMouseDown="ScrollViewer_OnPreviewMouseDown"
  3. PreviewMouseMove="ScrollViewer_OnPreviewMouseMove"
  4. PreviewMouseUp="ScrollViewer_OnPreviewMouseUp"
  5. >
  6. <StackPanel x:Name="stackPanel" Orientation="Horizontal" HorizontalAlignment="Left">
  7. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick" />
  8. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  9. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  10. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  11. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  12. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  13. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  14. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  15. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  16. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  17. <Button Width="240" Height="100" Margin="10" Click="ButtonBase_OnClick"/>
  18. </StackPanel>
  19. </ScrollViewer>

 代码

  1. Point initialMousePoint = new();
  2. double horizontalOffset = 1;
  3. bool isMouseDown = false;
  4. private double mouseDist = 0;
  5. private void ScrollViewer_OnPreviewMouseDown(object sender, MouseButtonEventArgs e) {
  6. initialMousePoint = e.GetPosition(scrollViewer);
  7. horizontalOffset = scrollViewer.HorizontalOffset;
  8. isMouseDown = true;
  9. e.Handled = false;
  10. }
  11. private void ScrollViewer_OnPreviewMouseMove(object sender, MouseEventArgs e) {
  12. if (isMouseDown && e.LeftButton == MouseButtonState.Pressed) {
  13. scrollViewer.ScrollToHorizontalOffset(horizontalOffset + (initialMousePoint.X - e.GetPosition(scrollViewer).X));
  14. }
  15. e.Handled = false;
  16. }
  17. private void ScrollViewer_OnPreviewMouseUp(object sender, MouseButtonEventArgs e) {
  18. isMouseDown = false;
  19. e.Handled = false;
  20. mouseDist = (e.GetPosition(scrollViewer) - initialMousePoint).Length;
  21. }
  22. private void ButtonBase_OnClick(object sender, RoutedEventArgs e) {
  23. if (mouseDist < 1) {
  24. if (sender is Button btn) {
  25. btn.Content = DateTime.Now.Millisecond.ToString();
  26. }
  27. }
  28. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/582799
推荐阅读
相关标签
  

闽ICP备14008679号