代码之家  ›  专栏  ›  技术社区  ›  Wolfgang Jacques

如何判断哪个WPF控件调用了命令?[复制品]

  •  0
  • Wolfgang Jacques  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我有三个与同一命令相关联的按钮:

    <StackPanel>
        <Button Name="Btn1" Content="Test 1" Command="{Binding CmdDoSomething}" />
        <Button Name="Btn2" Content="Test 2" Command="{Binding CmdDoSomething}" />
        <Button Name="Btn3" Content="Test 3" Command="{Binding CmdDoSomething}" />
    </StackPanel>
    

    如何判断哪个按钮调用了命令或将此信息传递给方法调用?

    CmdDoSomething = new DelegateCommand(
        x => DvPat(),
        y => true
    );
    

    这是我的delegatecommand类:

    public class DelegateCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    
        private readonly Predicate<object> _canExecute;
        public bool CanExecute(object parameter) => _canExecute == null ? true : _canExecute(parameter);
    
        private readonly Action<object> _execute;
        public void Execute(object parameter) => _execute(parameter);
    
        public DelegateCommand(Action<object> execute) : this(execute, null) { }
        public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Vadim Martynov    6 年前

    Commands paradigm DelegateCommand 包含可传递到处理程序的参数 CommandParameter 属性并在处理程序中使用它:

    <StackPanel>
        <Button Name="Btn1" Content="Test 1" Command="{Binding CmdDoSomething}" CommandParameter="Test 1" />
        <Button Name="Btn2" Content="Test 2" Command="{Binding CmdDoSomething}" CommandParameter="Test 2" />
        <Button Name="Btn3" Content="Test 3" Command="{Binding CmdDoSomething}" CommandParameter="Test 3" />
    </StackPanel>
    
    CmdDoSomething = new DelegateCommand(
        parameter => DvPat(parameter),
        y => true
    );
    

    此参数还可用于在以下情况下评估命令的状态: CanExecute(object param) 被称为。