17

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

我认为我的 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();
    }
}
4

3 回答 3

12

更改ActionAction<T>使其接受一个参数(可能只是Action<object>最简单的)。

private readonly Action<object> _handler;

然后只需将参数传递给它:

public void Execute(object parameter)
{
    _handler(parameter);
}
于 2012-10-28T20:20:00.720 回答
5

你可以做

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

然后,当然有你的AddPhone

public void AddPhone(string x)
{
    //handle x
}
于 2018-01-04T00:08:54.517 回答
2

您可以简单地执行此操作(无需更改 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;
    ...
}
于 2015-05-26T04:04:54.097 回答