How to identify which button clicked? (MVVM)

You probably shouldn't, but if you want to, you can use CommandParameter=""

You should just use 2 ICommands though.

XAML:

<Button Command="{Binding ClickCommandEvent}" CommandParameter="Jack"/>

ViewModel:

public RelayCommand ClickCommandEvent { get; set; }

public SomeClass()
{
    ClickCommandEvent = new RelayCommand(ClickExecute);
}

public void ClickExecute(object param)
{
    System.Diagnostics.Debug.WriteLine($"Clicked: {param as string}");

    string name = param as string;
    if (name == "Jack")
        HighFive();
}

and your RelayCommand class would be this boiler plate:

public class RelayCommand : ICommand
{
    #region Fields
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion

    #region Constructors
    public RelayCommand(Action<object> execute) : this(execute, null) { }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion

    #region ICommand Members
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
    #endregion
}

This will give you the clicked Button :

<Button Command="{Binding ClickCommand}" 
        CommandParameter="{Binding RelativeSource={RelativeSource Self}}"/>

You're not supposed to bind all buttons to the same command. Just make a different command for each button.

Tags:

C#

Wpf

Button

Mvvm