Consider using inheritance with ReactiveUI.
I have base ViewModel class with DoSomethingCommand. ‘CanExecute’ for this command depends on property Prop1
public class A : ReactiveObject
{
public int Prop1 { get {...} set {...} }
public ReactiveCommand DoSomethingCommand { get; private set; }
public A()
{
IObservable<bool> canDoSomething = this.WhenAny(vm => vm.Prop1, p1 => CanDoSomething());
DoSomethingCommand = new ReactiveCommand(canDoSomething);
DoSomethingCommand.Subscribe(x => DoSomething());
}
protected virtual bool CanDoSomething()
{
return ...
}
}
In inherited class the ‘CanExecute’ for this command depends additionally on property Prop2
public class B : A
{
public int Prop2 { get {...} set {...} }
public B()
{
//Senseless code. For explanation only
IObservable<bool> canDeleteExecute = this.WhenAny(vm => vm.Prop1, vm => vm.Prop2, (p1, p2) => CanDoSomething());
}
}
What is the best practice to create command and make ‘CanExecute’ dependent on properties from base and inherited classes?
Of course, I want inherited classes shouldn’t change when ‘CanExecute’ in base class become additionally depend on AnotherProp property.
I’ve written extension class for WhenAny. It’s much more to do for making it like WhenAny in ReactiveUI, but enough for me now. First, look at usage:
Implementation:
And uninteresting, in this context, helper class for getting property name from expression: