如何使用ReactiveCommand可以执行

use*_*005 1 command prism reactiveui

我是WPF的新手,使用reactUI实施应用程序。我有一个按钮,并为其添加了命令处理程序。只想在canExecute为true时才调用该方法。

在视图模型中,我已经定义了它

public bool canExecute 
{
  get { return _canExecute;}
  set { _canExecute = value;}
}

Bind()
{
 AddRecord = new ReactiveCommand(_canExecute);

    AddRecord .Subscribe(x => 
    {
       AddR()
}
}
void AddR()
{
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用。如何将其转换为System.IObservable?

Ana*_*tts 6

正如@jomtois所提到的,您需要修复CanExecute的声明:

bool canExecute;
public bool CanExecute {
    get { return canExecute; }
    set { this.RaiseAndSetIfChanged(ref canExecute, value); }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以编写:

AddRecord = new ReactiveCommand(this.WhenAnyValue(x => x.CanExecute));
Run Code Online (Sandbox Code Playgroud)

为什么要付出所有这些努力?这样可以使CanExecute发生更改时,ReactiveCommand自动启用/禁用。但是,这种设计非常必要,我不会创建CanExecute布尔值,而是考虑如何组合与具有语义含义的ViewModel相关的属性。