WPF命令绑定捕获命令参数eventArgs

定义delegateCommand:

public class DelegateCommand<T> : ICommand
    {
        private readonly Predicate<T> _canExecute;
        private readonly Action<T> _execute;


        public DelegateCommand(Action<T> execute) : this(execute, null)
        {
        }

        public DelegateCommand(Action<T> execute, Predicate<T> canExecute)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }

            _execute = execute;
            _canExecute = canExecute;
        }

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute((T)parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        #endregion
    }

定义eventTriggerAction :

 public class EventTriggerAction : TriggerAction<DependencyObject>
    {
        protected override void Invoke(object parameter)
        {
            if (CommandParameter != null)
            {
                Command?.Execute(CommandParameter);
            }
            else
            {
                Command?.Execute(parameter);
            }
        }

        // Using a DependencyProperty as the backing store for Command.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register("Command", typeof(ICommand), typeof(EventTriggerAction),
                new PropertyMetadata(null));


        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CommandParameter.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.Register("CommandParameter", typeof(object), typeof(EventTriggerAction),
                new PropertyMetadata(null));


        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }
    }

前台绑定:

   <i:Interaction.Triggers>
        <i:EventTrigger   EventName="KeyDown">
            <local:EventTriggerAction  Command="{Binding KeyDownCMD}"></local:EventTriggerAction>
        </i:EventTrigger>
    </i:Interaction.Triggers>

源码:https://files.cnblogs.com/files/lizhijian/2021-01-04-WPF-CommandWithParameter.rar

原文地址:https://www.cnblogs.com/congqiandehoulai/p/14262355.html