0

I have three Buttons associated with the same command:

<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>

How can I tell which Button invoked the command or pass this information to the method call?

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

Here's my DelegateCommand Class:

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;
    }

}
Wolfgang Jacques
  • 769
  • 6
  • 15
  • The easiest way would be to pass in command parameters to the command. Have a look at this thread on how its done. https://stackoverflow.com/questions/32064308/pass-command-parameter-to-method-in-viewmodel-in-wpf – Adam Jan 22 '19 at 15:40
  • 2
    Also, for what it's worth, your Command object is not supposed to know anything about which control invokes the command. That's kind of the whole point of having a Command object in the first place. – Robert Harvey Jan 22 '19 at 15:41

1 Answers1

4

Commands paradigm and DelegateCommand contains parameter which can you pass into handler with CommandParameter attribute and use it in the handler:

<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
);

This parameter can also be used to evaluate the state of the command when CanExecute(object param) is called.

Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43