Pass Command Parameter to RelayCommand
By Michael Detras
Shows an example on how to pass a command parameter to a RelayCommand.
I've seen many people asking how to pass a command parameter to a RelayCommand object.
The RelayCommand is created by Josh Smith and he has written an MSDN article using one. However, he has only shown the RelayCommand class that does not support passing of command parameter. Here is the other version.
public class RelayCommand<T> : ICommand
{
#region Fields
readonly Action<T> _execute = null;
readonly Predicate<T> _canExecute = null;
#endregion // Fields
#region Constructors
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
/// <summary>
/// Creates a new command.
/// </summary>
/// <param name="execute">The execution logic.</param>
/// <param name="canExecute">The execution status logic.</param>
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute
= canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add
{ CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
#endregion // ICommand Members
}
To use this, create a property where the Command property of the control will be bounded. Also, the execute and canExecute methods should accept a parameter.
public ICommand MyCommand
{
get
{
if (myCommand == null)
{
myCommand = new RelayCommand<object>(CommandExecute, CanCommandExecute);
}
return myCommand;
}
}
private void CommandExecute(object parameter)
{
// Code here
}
private bool CanCommandExecute(object parameter)
{
// Code here
return true;
}
In the XAML, just bind the Command and CommandParameter properties.
<Button Command="{Binding MyCommand}"
CommandParameter="{Binding ElementName=AnotherElement, Path=MyProperty}"/>
Pass Command Parameter to RelayCommand (12928 Views)