Continuing down the path to MVVM, I have come to button commands. After quite a bit of trial and error I finally have a working example of a Button_Click
command using ICommand
.
My issue is that now I have a generic event made, I can't get which button was clicked to apply some logic to it. In my example, I have not used anything where I could get the Sender
information. Usually something like this below using RoutedEventArgs
:
Button button = (Button)sender;
So this is what I have so far.
The ICommand
class:
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
And the code to make the action:
private ICommand _clickCommand;
public ICommand ClickCommand => _clickCommand ?? (_clickCommand = new CommandHandler(MyAction, _canExecute));
public ViewModelBase()
{
_canExecute = true;
}
public void MyAction()
{
//Apply logic here to differentiate each button
}
And the XAML,
<Button Command="{Binding ClickCommand}" Style="{StaticResource RedButtonStyle}">MyButton</Button>
How would I go about identifying which button is being clicked when binding the same command to other buttons?