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 RadioButtonUserSelectionBehavior : Behavior { public static readonly DependencyProperty UserSelectionCommandProperty = DependencyProperty.Register( nameof(UserSelectionCommand), typeof(ICommand), typeof(RadioButtonUserSelectionBehavior)); public ICommand UserSelectionCommand { get => (ICommand)GetValue(UserSelectionCommandProperty); set => SetValue(UserSelectionCommandProperty, value); } public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register( nameof(CommandParameter), typeof(object), typeof(RadioButtonUserSelectionBehavior)); 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 += OnChecked; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PreviewMouseDown -= OnPreviewMouseDown; AssociatedObject.PreviewKeyDown -= OnPreviewKeyDown; AssociatedObject.Checked -= OnChecked; } 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 OnChecked(object sender, RoutedEventArgs e) { if (_isUserInteraction && UserSelectionCommand?.CanExecute(CommandParameter) == true) { var parameter = new Tuple(CommandParameter, AssociatedObject.Content); UserSelectionCommand.Execute(parameter); } _isUserInteraction = false; } } }