ReactiveCommand.Create 抛出 "NotSupportedException":"Index expressions are only supported with constants."

ReactiveCommand.Create throws "NotSupportedException": "Index expressions are only supported with constants."

以下行抛出运行时异常:

Accept = ReactiveCommand.Create(this.WhenAnyValue(x => x.Canexecute()));

代码如下:

public class InstructionsViewModel : ReactiveObject
{
    public InstructionsViewModel()
    {
        Accept = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanExecute));
        Accept.Subscribe(x =>
          {
             Debug.Write("Hello World");
          });
    }

        public ReactiveCommand<object> Accept { get; }

    bool _canExecute;
    public bool CanExecute { get { return _canExecute; } set { this.RaiseAndSetIfChanged(ref _canExecute, value); } }
}

错误:

Cannot convert lambda expression to type 'IObserver' because it is not a delegate type

我也试过以下方法:

    public InstructionsViewModel()
    {
        Accept = ReactiveCommand.Create(this.WhenAnyValue(x => x.Canexecute()));
        Accept.Subscribe(x =>
        {
            Debug.Write("Hello World");
        });
    }

    public ReactiveCommand<object> Accept { get; }


    public bool Canexecute() => true;

我收到以下错误:

An exception of type 'System.NotSupportedException' occurred in ReactiveUI.dll but was not handled in user code

Additional information: Index expressions are only supported with constants.

Windows Phone 10 是否支持此功能?

我猜你的问题不在于 ReactiveCommand,而在于 WhenAnyValue

WhenAnyValue 接受一个 属性,而你用一个方法喂它,这会导致 运行 时间异常 (see the sourcecode).

检查这是否有效(我将 CanExecute 更改为 属性 而不是方法):

public InstructionsViewModel()
{
    Accept = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanExecute));
    Accept.Subscribe(x =>
    {
        Debug.Write("Hello World");
    });
}

public ReactiveCommand<object> Accept { get; }

private bool _canExecute;
public bool CanExecute { get { return _canExecute; } set { this.RaiseAndSetIfChanged(ref _canExecute, value); } }

此外,作为一般性建议 - 不要嵌套调用,这会使调试更加困难。您应该将创建命令分成两行:

var canExecute = this.WhenAnyValue(x => x.CanExecute)
Accept = ReactiveCommand.Create(canExecute);