1
votes

I'm new in WPF, implementing application using reactiveUI. I have one button and added command handler for it. want to call the method only when canExecute is true.

in viewmodel, i have defined it

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

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

    AddRecord .Subscribe(x => 
    {
       AddR()
}
}
void AddR()
{
}

but its not working. how to convert it in to System.IObservable?

1
I don't know if you are using an older version of ReactiveUI, but the current version takes in an IObservable<bool> as a constructor parameter. Looks like you are passing in a bool, which I don't know but from just what you have, would be false anyway and not support changes. At a minimum you might want: new ReactiveCommand(this.WhenAnyValue(t => t.canExecute).Select(b => b==true))Jon Comtois

1 Answers

6
votes

As @jomtois mentions, you need to fix your declaration of CanExecute:

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

Then, you can write:

AddRecord = new ReactiveCommand(this.WhenAnyValue(x => x.CanExecute));

Why go to all this effort? This makes it so that when CanExecute changes, ReactiveCommand automatically enables / disables. However, this design is pretty imperative, I wouldn't create a CanExecute boolean, I'd think about how I can combine properties related to my ViewModel that have a semantic meaning.