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.Input; namespace AIK.Behaviors { public class ClickBehavior : Behavior { public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(ClickBehavior)); public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(nameof(CommandParameter), typeof(object), typeof(ClickBehavior)); public ICommand Command { get => (ICommand)GetValue(CommandProperty); set => SetValue(CommandProperty, value); } public object CommandParameter { get => GetValue(CommandParameterProperty); set => SetValue(CommandParameterProperty, value); } protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonDown += OnMouseLeftButtonDown; AssociatedObject.Loaded += OnLoaded; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseLeftButtonDown -= OnMouseLeftButtonDown; AssociatedObject.Loaded -= OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { // 调试信息 //System.Diagnostics.Debug.WriteLine($"ClickBehavior loaded on {AssociatedObject.GetType().Name}"); //System.Diagnostics.Debug.WriteLine($"Command: {Command}"); //System.Diagnostics.Debug.WriteLine($"CommandParameter: {CommandParameter}"); } private void OnMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (Command?.CanExecute(CommandParameter) == true) { Command.Execute(CommandParameter); e.Handled = true; } } } }