KyloRen
KyloRen

Reputation: 2741

How to identify which button clicked? (MVVM)

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?

Upvotes: 6

Views: 5720

Answers (5)

Ehsan
Ehsan

Reputation: 785

Sometimes this is unavoidable to direct several commands to the same function to reuse the same code. I found this approach the easiest way to identify which control has been clicked. In the Xaml I set ElementName for both buttons like this:

      <Button Grid.Row="0"
              Grid.Column="0"
              Content="Read File"                  
              Command="{Binding ReadProButtonClick}"
              CommandParameter="{Binding ElementName=ReadFile}"/>          

      <Button Grid.Row="0"                  
              Grid.Column="1"
              Content="Batch Convert"                 
              Command="{Binding ReadProButtonClick}"
              CommandParameter="{Binding ElementName=BatchMode}"/>

And then in the ViewModel, I get the name of the buttons like this:

 Private void ReadProButton(Object context) {           
        Controls.Button btnClicked = CType(context, System.Windows.Controls.Button)           
        processName = btnClicked.Name
        ...
 }

So, processName will be BatchMode or ReadFile depends on what the user clicked on.

Upvotes: 0

MattE
MattE

Reputation: 1114

This is where WPF relies on too much code for simple actions. I mean 30 lines of code for handling a button click is a little ridiculous but somehow we talk ourselves into it being a "good" thing because it follws a pattern.

Excessive code is excessive code. There is no reason why this should be this complicated.

Upvotes: 1

Xander Luciano
Xander Luciano

Reputation: 3893

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
}

Upvotes: 5

AnjumSKhan
AnjumSKhan

Reputation: 9827

This will give you the clicked Button :

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

Upvotes: 3

Thomas Levesque
Thomas Levesque

Reputation: 292685

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

Upvotes: 1

Related Questions