RadioButtonUserSelectionBehavior.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 RadioButtonUserSelectionBehavior : Behavior<RadioButton>
  13. {
  14. public static readonly DependencyProperty UserSelectionCommandProperty =
  15. DependencyProperty.Register(
  16. nameof(UserSelectionCommand),
  17. typeof(ICommand),
  18. typeof(RadioButtonUserSelectionBehavior));
  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(RadioButtonUserSelectionBehavior));
  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 += OnChecked;
  41. }
  42. protected override void OnDetaching()
  43. {
  44. base.OnDetaching();
  45. AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
  46. AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;
  47. AssociatedObject.Checked -= OnChecked;
  48. }
  49. private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
  50. {
  51. _isUserInteraction = true;
  52. }
  53. private void OnPreviewKeyDown(object sender, KeyEventArgs e)
  54. {
  55. if (e.Key == Key.Space)
  56. {
  57. _isUserInteraction = true;
  58. }
  59. }
  60. private void OnChecked(object sender, RoutedEventArgs e)
  61. {
  62. if (_isUserInteraction && UserSelectionCommand?.CanExecute(CommandParameter) == true)
  63. {
  64. var parameter = new Tuple<object, object>(CommandParameter, AssociatedObject.Content);
  65. UserSelectionCommand.Execute(parameter);
  66. }
  67. _isUserInteraction = false;
  68. }
  69. }
  70. }