ReactiveCommand.Create throws" NotSupportedException":"索引表达式仅支持常量。"

时间:2015-12-17 14:15:31

标签: win-universal-app uwp reactiveui

以下行引发运行时异常:

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

错误:

  

无法将lambda表达式转换为&#39; IObserver&#39;因为   它不是委托类型

我还尝试过以下方法:

    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;

我收到以下错误:

  

类型&#39; System.NotSupportedException&#39;的例外情况发生在   ReactiveUI.dll但未在用户代码中处理

     

其他信息:仅支持索引表达式   常数。

Windows Phone 10上是否支持此功能?

1 个答案:

答案 0 :(得分:1)

我猜您的问题不在于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);
相关问题