MVVM RelayCommand parameter null

183 Views Asked by At

I'm struggling with a problem related to the RelayCommand class. I'm trying to pass a parameter to a method to execute through the RelayCommand but I cannot make it work. The method is correctly called but the param passed is always null.

My RelayCommand class:

    public class RelayCommand : ICommand
{
    #region Fields

    private readonly Action<object> _execute;
    private 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 // ICommand Members
}

I'm trying to pass a simple text value

<Button
   Margin="0,8,8,0"
   Content="Ok"
   IsDefault="True"
   CommandParameter="Sample"
   Style="{StaticResource MaterialDesignFlatButton}">
         <i:Interaction.Triggers>
             <i:EventTrigger
                 EventName="Click">                                        
                 <i:InvokeCommandAction
                     Command="{Binding CreateNewCommand}" />
             </i:EventTrigger>
         </i:Interaction.Triggers>
 </Button>

My Command:

public ICommand CreateNewCommand
    {
        get
        {
            return  new RelayCommand(param => CreateNew(param)); 
        }
    }

No matter what the obj is always null.

private void CreateNew(object obj)
    {
        // obj is null
    }

What am I doing wrong? Thank you very much!

2

There are 2 best solutions below

0
Lennart On BEST ANSWER

The CommandParamter has to be passed on the InvokeCommandAction, not the Button:

<Button
   Margin="0,8,8,0"
   Content="Ok"
   IsDefault="True"   
   Style="{StaticResource MaterialDesignFlatButton}">
         <i:Interaction.Triggers>
             <i:EventTrigger
                 EventName="Click">                                        
                 <i:InvokeCommandAction
                     Command="{Binding CreateNewCommand}"
                     CommandParameter="Sample" />
             </i:EventTrigger>
         </i:Interaction.Triggers>
 </Button>
0
Clemens On

You should simply bind the Button's Command property:

<Button ...
    Command="{Binding CreateNewCommand}"
    CommandParameter="Sample" />