Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to MVVM Command

Tags:

c#

mvvm

wpf

Does anyone knows how to pass parameters to Command using CommandHandler? Let's assume I would like to pass string hard coded value from XAML. I know how to pass from XAML, but not how to handle it in MVVM code behind. The code below works fine if there is no need to pass any parameters.

public ICommand AttachmentChecked
{
    get
    {
        return _attachmentChecked ?? (_attachmentChecked = new CommandHandler(() => ExecuteAttachmentChecked(), CanExecuteAttachmentChecked()));
    }
}

private void ExecuteAttachmentChecked()
{        
}

private bool CanExecuteAttachmentChecked()
{
    return true;
}

CommandHandler:

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();
    }
}
like image 921
lucas Avatar asked Feb 12 '16 19:02

lucas


2 Answers

You need to change two things

1.Change your Commandhandler to accept parameter

 public class CommandHandler : ICommand
{
    private Action<object> _action;
    private bool _canExecute;
    public CommandHandler(Action<object> action, bool canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

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

    public event EventHandler CanExecuteChanged;

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

2.Change the method to accept the CommandParameter:

public ICommand AttachmentChecked
{
    get
    {
        return _attachmentChecked ?? (_attachmentChecked = new CommandHandler(param => ExecuteAttachmentChecked(param), CanExecuteAttachmentChecked()));
    }
}

private void ExecuteAttachmentChecked(object param)
{
 //param will the value of `CommandParameter` sent from Binding
}

private bool CanExecuteAttachmentChecked()
{
    return true;
}
like image 127
Kylo Ren Avatar answered Oct 14 '22 22:10

Kylo Ren


You should just write your string into CommandParameter:

<Button Command="{Binding NextCommand}" 
CommandParameter="Hello" 
Content="Next" />

and change from:

private Action _action;
private bool _canExecute;

to allow accept parameters:

readonly Action<object> _execute;        
readonly Predicate<object> _canExecute;

Assuming that you are using RelayCommand in parameter obj of method DoSmth will be "Hello":

public RelayCommand YourCommand { get; set; }
public YourViewModel()
{
    NextCommand = new RelayCommand(DoSmth);
}

private void DoSmth(object obj)
{
    Message.Box(obj.ToString()); 
}
like image 44
StepUp Avatar answered Oct 14 '22 21:10

StepUp