如何将字符串和int都发送到ICommand?

时间:2018-08-11 15:36:48

标签: c# wpf

我有一个如下所示的ViewModel命令:

// Category Page
private ICommand openPageCmd;
public ICommand OpenPageCmd =>
    openPageCmd ??
    (openPageCmd = new Command<string>((pageType) => settingsPage.OpenPage(pageType)));

但是我不想发送一个字符串,而是发送一个ID(一个整数)和一个Name(一个字符串)。有人可以告诉我该怎么做吗?

1 个答案:

答案 0 :(得分:3)

您可以通过实现ICommand来创建自己的命令。创建一个具有所需参数的构造函数的命令。

请参阅:

public class MyCommand : ICommand
{
    private int _id;
    private string _name;

    public MyCommand(int id, string name)
    {
        _id = id;
        _name = name;
    }

    public bool CanExecute(object parameter) => true;

    public void Execute(object parameter)
    {
        //TODO: Add your implementation
    }

    public event EventHandler CanExecuteChanged;
}

或者更好地,创建自己的中继命令(通用可重用命令):

public class RelayCommand<T> : ICommand
{
    private readonly T _argument;
    private readonly Action<T> _execute;

    public RelayCommand(T argument, Action<T> execute)
    {
        _execute = execute;
        _argument = argument;
    }

    public bool CanExecute(object parameter) => true;

    public void Execute(object parameter)
    {
        _execute(_argument);
    }

    public event EventHandler CanExecuteChanged;
}

视图模型

public class MyViewModel
{
    private SettingsPage settingsPage = new ...;

    public int Id { get; set; }
    public string Name { get; set; }

    public MyViewModel()
    {
        OpenPageCmd =
            new RelayCommand<MyViewModel>(this, vm => settingsPage.OpenPage(vm.Id, vm.Name));
    }

    public ICommand OpenPageCmd { get; }
}

这允许命令随时使用视图模型的当前值。