CheckBoxUserSelectionBehavior.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 CheckBoxUserSelectionBehavior : Behavior<CheckBox>
  13. {
  14. public static readonly DependencyProperty UserSelectionCommandProperty =
  15. DependencyProperty.Register(
  16. nameof(UserSelectionCommand),
  17. typeof(ICommand),
  18. typeof(CheckBoxUserSelectionBehavior));
  19. public ICommand UserSelectionCommand
  20. {
  21. get => (ICommand)GetValue(UserSelectionCommandProperty);
  22. set => SetValue(UserSelectionCommandProperty, value);
  23. }
  24. public static readonly DependencyProperty CommandParameterProperty =
  25. DependencyProperty.Register(
  26. nameof(CommandParameter),
  27. typeof(object),
  28. typeof(CheckBoxUserSelectionBehavior));
  29. public object CommandParameter
  30. {
  31. get => GetValue(CommandParameterProperty);
  32. set => SetValue(CommandParameterProperty, value);
  33. }
  34. private bool _isUserInteraction = false;
  35. protected override void OnAttached()
  36. {
  37. base.OnAttached();
  38. AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
  39. AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
  40. AssociatedObject.Checked += OnCheckedChanged;
  41. AssociatedObject.Unchecked += OnCheckedChanged;
  42. }
  43. protected override void OnDetaching()
  44. {
  45. base.OnDetaching();
  46. AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
  47. AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;
  48. AssociatedObject.Checked -= OnCheckedChanged;
  49. AssociatedObject.Unchecked -= OnCheckedChanged;
  50. }
  51. private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
  52. {
  53. _isUserInteraction = true;
  54. }
  55. private void OnPreviewKeyDown(object sender, KeyEventArgs e)
  56. {
  57. if (e.Key == Key.Space)
  58. {
  59. _isUserInteraction = true;
  60. }
  61. }
  62. private void OnCheckedChanged(object sender, RoutedEventArgs e)
  63. {
  64. if (_isUserInteraction && UserSelectionCommand?.CanExecute(CommandParameter) == true)
  65. {
  66. var parameter = new Tuple<object, bool>(CommandParameter, AssociatedObject.IsChecked == true);
  67. UserSelectionCommand.Execute(parameter);
  68. }
  69. _isUserInteraction = false;
  70. }
  71. }
  72. }