3

I can create a command like this which checks for some property of my view model if it can execute:

AddNewSectionCommand = ReactiveCommand
    .CreateFromTask(() => AddNewSectionAsync(NewSectionTitle),
                    this.WhenAny(x => x.NewSectionTitle, x => !string.IsNullOrWhiteSpace(x.Value)));

Is it also possible to do this for the CommandParameter I pass in via WPF, and if, how? Because sometimes I directly want to use something in the UI as the parameter for a command but also want to check validity before. Until now, I have to do this by binding the value to a view model property and use the above which clutters my view models with a lot of superfluous stuff.

rabejens
  • 7,594
  • 11
  • 56
  • 104

1 Answers1

3

No, there’s no CommandParameter for canExecute. The vm property route is the way to go. All the ReactiveUI “getting started” type examples have always used this method (e.g. username/password), which makes sense because the vm should be responsible for determining executability. One of the main reasons being that it’s a lot easier to unit test. So I feel the extra property/properties that get added to the vm is well worth it and not superfluous at all.

Colt Bauman
  • 564
  • 3
  • 9
  • 1
    In regard to the view model having the only control about what can be executed and what not, this absolutely makes sense. In the past I used a mix of view model and code behind for small, not too complex self contained user controls (like a text box and a button where the button opens a file selector and populates the text box accordingly), I'll now use a view model for everything. – rabejens Dec 19 '18 at 10:57
  • Usually your decision to allow execution of a command should be based on model/view model available data anyway. Eg you tend to bind the selected item anyway so that is view model data. You don't tend to make it on view related data very often. So having it not available as a parameter makes sense from.that point of view. – Glenn Watson Dec 19 '18 at 19:53
  • 2
    I have a calendar view with 4 buttons, move month, move year, allowed back and forth, within a specified date range. I bound all buttons to the same command passing -1, -12, 12, and 1 number of months respectively. The command parameter is a const value inline the button. Isn't there a way to set up can execute with RxUI so that it checks whether the new calculated date exceeds the allowed date criteria? Does that mean I have no choice but to create 4 different commands? – Shimmy Weitzhandler Nov 17 '19 at 03:47
  • 2
    I had a similar problem that ended up with mulitple commands, each command corresponding to a button. What I did was create some "dummy-functions" all calling the same central function. Like DoThis("new"), DoThis("edit"), DoThis("whatever") and finally function DoThis(string doWhat). I really miss the possibility of defining a "canExecute"-function based on CommandParameter. – okieh Aug 28 '20 at 16:19