1. 程式人生 > 實用技巧 >WPF命令繫結捕獲命令引數eventArgs

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