0

How to use 2 different commands for 2 different buttons in a viewmodel.

MY requirement is to use 2 buttons in my page.

I have implemented for 1 button , but not able to implement for multiple buttons .

Can anyone provide me a example of using multiple commands in viewmodel using MVVM.

I am very new to MVVM , so please help me out.

3
  • Are you using PRISM library or want to achieve it without it? Commented Oct 25, 2017 at 10:39
  • @Sagar I am not using PRISM library Commented Oct 25, 2017 at 10:52
  • A command in a view model is typically a property of type ICommand. You can have as many such property as you like in any view model class. So what is your question? Commented Oct 25, 2017 at 10:55

1 Answer 1

1

1) Create RelayCommand class:

public class RelayCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public RelayCommand(Predicate<object> canExecute, Action<object> execute)
    {
        this._canExecute = canExecute;
        this._execute = execute;
    }

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

    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

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

2) Create ICommand properties in your VM:

public ICommand Command1 { get { return new RelayCommand(e => true, this.MethodForCommand1); } }
public ICommand Command2{ get { return new RelayCommand(e => true, this.MethodForCommand2); } }
private void MethodForCommand1(object obj){ //Type your code for Command1 }
private void MethodForCommand2(object obj){ //Type your code for Command2 }

3) Bind command in view:

    <Button Content="Button 1" Command="{Binding Command1}"/>
    <Button Content="Button 2" Command="{Binding Command2}"/>

Hope it's help ;)

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

1 Comment

Thank u so much , it helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.