Xamarin.Forms 如何将Command 构造函数的execute 和canExecute 参数包含到一个方法中?

How to include the execute and canExecute parameters of Command constructor into a single method in Xamarin.Forms?

我有以下代码

public partial class CopyViewModel : BaseViewModel
{

    public ICommand CancelCmd { private set; get; }

    public CopyViewModel(string clickedDeckName, string clickedDeckDescription)
    {
        CancelCmd = new Command(
        execute: () =>
        {
            var a = 1;
        },
        canExecute: () => 1 < 2);
    }
}

但我希望能够像这样写一些东西:

CancelCmd = new Command(CancelMethod);

但是我应该如何编码包含 executecanExecuteCancelMethod


此外,我收到以下错误:

第 1 部分

我通常做的是这样的:

SGTryAgainCommand = new Command(
    execute: SGTryAgain, 
    canExecute: SGTryAgainCanExecute);

哪里

private void SGTryAgain()
{
    // Do something
}

private Boolean SGTryAgainCanExecute()
{
    // Evaluate if command can execute!
}

如果你像这样在 SGTryAgain() 中移动 SGTryAgainCanExecute()

private void SGTryAgain()
{
    if (SGTryAgainCanExecute())
        SetInstanceOfSyncGateway();
}

那么你也许可以实现你想要的,只需调用

SGTryAgainCommand = new Command(SGTryAgain);

警告

我强烈建议您不要这样做,因为它会有一些缺点,例如:

  • 如果您将 Command 绑定到 Button,那么不显式设置 canExecute 将导致 Button 被启用,即使它无法执行。这是 Button 的一个很好的行为,实际上:如果 canExecute returns false.
  • 能够显示为禁用

第 2 部分

如何解决您遇到的错误

至于你得到的错误,你可以改变你的代码如下:

OKCommand = new Xamarin.Forms.Command(execute: (x)=>OK(), canExecute: OKCanExecute);

为什么会出现该错误?

Command 构造函数有两个重载

Command(Action<object> execute, Func<object, bool> canExecute)
Command(Action execute, Func<bool> canExecute)

在您的代码中,因为您用于 canExecute 的函数具有签名

// Takes an object and returns a boolean
Func<object, bool> canExecute)

你隐式地选择了你的函数接受参数的重载,因此你被迫在你的执行方法中接受一个参数!所以你必须写

// just ignore the x object...
OKCommand = new Xamarin.Forms.Command(execute: (x)=>OK(), canExecute: OKCanExecute);

如上所说,或者你要修改你的OK方法签名,定义like

private void OK(object x)
{
    throw new NotImplementedException();
}

在这种情况下你可以重新写

OKCommand = new Xamarin.Forms.Command(execute: OK, canExecute: OKCanExecute);