将参数传递给ICommand

时间:2012-10-28 20:09:30

标签: c# wpf

我有一个简单的按钮,在执行时使用命令,这一切都正常,但我想在单击按钮时传递一个文本参数。

我认为我的XAML没问题,但我不确定如何编辑我的RelayCommand类来接收参数:

<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();
    }
}

3 个答案:

答案 0 :(得分:9)

Action更改为Action<T>,以便获取参数(可能只是Action<object>最简单)。

private readonly Action<object> _handler;

然后简单地传递参数:

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

答案 1 :(得分:1)

您可以简单地执行此操作(无需更改RelayCommand或ICommand):

private RelayCommand _addPhoneCommand;
public RelayCommand AddPhoneCommand
{
    get
    {
        if (_addPhoneCommand == null)
        {
            _addPhoneCommand = new RelayCommand(
                (parameter) => AddPhone(parameter),
                (parameter) => IsValidPhone(parameter)
            );
        }
        return _addPhoneCommand;
    }
}

public void AddPhone(object parameter)
{
    var text = (string)parameter;
    ...
}

public void IsValidPhone(object parameter)
    var text = (string)parameter;
    ...
}

答案 2 :(得分:0)

你可以做到

public ICommand AddPhoneCommand
{
    get
    {
        return new Command<string>((x) =>
        {
            if(x != null) { AddPhone(x); }
        };
    }
}

然后,当然有你的AddPhone

public void AddPhone(string x)
{
    //handle x
}