| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- using Microsoft.Xaml.Behaviors;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- namespace TeamAAS_VP.Behaviors
- {
- public class CheckBoxUserSelectionBehavior : Behavior<CheckBox>
- {
- public static readonly DependencyProperty UserSelectionCommandProperty =
- DependencyProperty.Register(
- nameof(UserSelectionCommand),
- typeof(ICommand),
- typeof(CheckBoxUserSelectionBehavior));
- public ICommand UserSelectionCommand
- {
- get => (ICommand)GetValue(UserSelectionCommandProperty);
- set => SetValue(UserSelectionCommandProperty, value);
- }
- public static readonly DependencyProperty CommandParameterProperty =
- DependencyProperty.Register(
- nameof(CommandParameter),
- typeof(object),
- typeof(CheckBoxUserSelectionBehavior));
- public object CommandParameter
- {
- get => GetValue(CommandParameterProperty);
- set => SetValue(CommandParameterProperty, value);
- }
- private bool _isUserInteraction = false;
- protected override void OnAttached()
- {
- base.OnAttached();
- AssociatedObject.PreviewMouseDown += OnPreviewMouseDown;
- AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
- AssociatedObject.Checked += OnCheckedChanged;
- AssociatedObject.Unchecked += OnCheckedChanged;
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown;
- AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown;
- AssociatedObject.Checked -= OnCheckedChanged;
- AssociatedObject.Unchecked -= OnCheckedChanged;
- }
- private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
- {
- _isUserInteraction = true;
- }
- private void OnPreviewKeyDown(object sender, KeyEventArgs e)
- {
- if (e.Key == Key.Space)
- {
- _isUserInteraction = true;
- }
- }
- private void OnCheckedChanged(object sender, RoutedEventArgs e)
- {
- if (_isUserInteraction && UserSelectionCommand?.CanExecute(CommandParameter) == true)
- {
- var parameter = new Tuple<object, bool>(CommandParameter, AssociatedObject.IsChecked == true);
- UserSelectionCommand.Execute(parameter);
- }
- _isUserInteraction = false;
- }
- }
- }
|