将参数传递给 ICommand [英] Passing a parameter to ICommand

查看:67
本文介绍了将参数传递给 ICommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

Action 更改为 Action 以便它接受一个参数(可能只是 Action 是最简单的).

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

这篇关于将参数传递给 ICommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆