Passing a parameter to ICommand

c#, wpf

Solution

Change `Action` to `Action<T>` so that it takes a parameter (probably just `Action<object>` is easiest).

private readonly Action<object> _handler;

And then simply pass it the parameter:

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

Problem

I have a simple button that uses a command when executed, this is all working fine but I would like to pass a text parameter when the button is clicked. I think my XAML is ok, but I'm unsure how to edit my `RelayCommand` class to receive a parameter: ``` <Button x:Name="AddCommand" Content="Add" Command="{Binding AddPhoneCommand}" CommandParameter="{Binding Text, ElementName=txtAddPhone}" /> ``` ``` public class RelayCommand : ICommand { private readonly Action _handler; private bool _isEnabled; public RelayCommand(Action handler) { _handler = handler; } public bool IsEnabled { get { return _isEnabled; } set { if (value != _isEnabled) { _isEnabled = value; if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } } } public bool CanExecute(object parameter) { return IsEnabled; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _handler(); } } ```

Original source