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; } } 
2
  • The easiest way would be to pass in command parameters to the command. Have a look at this thread on how its done. stackoverflow.com/questions/32064308/… Commented Jan 22, 2019 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. Commented Jan 22, 2019 at 15:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thank you. I was not aware of CommandParameter.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.