SliderUserInteractionBehavior.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using Microsoft.Xaml.Behaviors;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Input;
  10. namespace TeamAAS_VP.Behaviors
  11. {
  12. public class SliderUserInteractionBehavior : Behavior<Slider>
  13. {
  14. public static readonly DependencyProperty UserInteractionCommandProperty =
  15. DependencyProperty.Register(
  16. nameof(UserInteractionCommand),
  17. typeof(ICommand),
  18. typeof(SliderUserInteractionBehavior));
  19. public ICommand UserInteractionCommand
  20. {
  21. get => (ICommand)GetValue(UserInteractionCommandProperty);
  22. set => SetValue(UserInteractionCommandProperty, value);
  23. }
  24. public static readonly DependencyProperty CommandParameterProperty =
  25. DependencyProperty.Register(
  26. nameof(CommandParameter),
  27. typeof(object),
  28. typeof(SliderUserInteractionBehavior));
  29. public object CommandParameter
  30. {
  31. get => GetValue(CommandParameterProperty);
  32. set => SetValue(CommandParameterProperty, value);
  33. }
  34. private bool _isUserDragging = false;
  35. private double _previousValue;
  36. protected override void OnAttached()
  37. {
  38. base.OnAttached();
  39. AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
  40. AssociatedObject.PreviewMouseUp += OnPreviewMouseUp;
  41. AssociatedObject.ValueChanged += OnValueChanged;
  42. }
  43. protected override void OnDetaching()
  44. {
  45. base.OnDetaching();
  46. AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
  47. AssociatedObject.PreviewMouseUp -= OnPreviewMouseUp;
  48. AssociatedObject.ValueChanged -= OnValueChanged;
  49. }
  50. private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
  51. {
  52. _isUserDragging = true;
  53. _previousValue = AssociatedObject.Value;
  54. }
  55. private void OnPreviewMouseUp(object sender, MouseButtonEventArgs e)
  56. {
  57. if (_isUserDragging)
  58. {
  59. _isUserDragging = false;
  60. }
  61. }
  62. private void OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
  63. {
  64. if (_isUserDragging && UserInteractionCommand?.CanExecute(CommandParameter) == true)
  65. {
  66. var parameter = new Tuple<object, double, double>(
  67. CommandParameter,
  68. _previousValue,
  69. AssociatedObject.Value);
  70. UserInteractionCommand.Execute(parameter);
  71. _previousValue = AssociatedObject.Value;
  72. }
  73. }
  74. }
  75. }