Passing Command Parameters

rreeves picture rreeves · Feb 6, 2012 · Viewed 14.6k times · Source

I'm trying to pass a command parameter with my command. I have commands in general working but passing a parameter doesn't seem to be going to well for me.

I'm trying to pass the UserName Property from the Hierarchical Data in my XAML. What am I doing wrong here.

I recieve and error trying to compile with the commands statement:

cannot convert from 'lambda expression' to 'System.Action'

<HierarchicalDataTemplate 
    DataType="{x:Type viewModel:UsersViewModel}" 
    ItemsSource="{Binding Children}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding UserName}">
            <TextBlock.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Edit" Command="{Binding EditCommand}" CommandParameter="{Binding UserName}"/>
                        <MenuItem Header="Delete"/>
                    </ContextMenu>
                </TextBlock.ContextMenu>
        </TextBlock>
    </StackPanel>
</HierarchicalDataTemplate>
private RelayCommand _editCommand;
    public ICommand EditCommand
    {
        get
        {
            if (_editCommand== null)
            {
                _editCommand= new RelayCommand(param => this.LoadUser(object parameter));
            }
            return _editCommand;
        }
    }

    public void LoadUser(object username)
    {

    } 

RelayCommand Class

public class RelayCommand : ICommand
{
    #region Fields

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

    #endregion // Fields

    #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 // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    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
}

Thanks for the help!

Answer

Felipe Castro picture Felipe Castro · Feb 6, 2012

You should not invoke the method, you should pass it as a parameter. Just replace new RelayCommand(param => this.LoadUser(object parameter)); for new RelayCommand(this.LoadUser);

Similar question here: RelayCommand lambda syntax problem