user3132998
user3132998

Reputation: 13

Correct usage of Commands (MVVM)

Question. I want to call a ViewModel-Command from my View. The problem I have is: The Command parameter can't be bound. Let's say. User clicks an Item. And I want to pass to my ViewModel Command a object which contains the properties: CurrentEntity, PositionX, PositionY. (It's a graphic oriented application. That's why I pass the X,Y positions to my viewmodel. I have to store the values in DB.) Now how would you solve that problem? How do you bind the Command from View and pass this specific command parameter object?

What I've done for now: I have a special interface which the Command definition which is implemented by the VM. THen... in my view (code-behind) I cast the DataContext to this Command-interface and then I call the Command from code behind (event handler). But it doesn't really make sense... Because in that case I could just call a simple ViewModel function. (If I don't need the CanExecute functionality) Is that a good design? What I dont like is... that some Command bindings are in XAML and some in code-behind. It's a bit confusing from a architectural perspective.

Am I clear enough?

Thanks

Upvotes: 1

Views: 89

Answers (1)

Breealzibub
Breealzibub

Reputation: 8095

The most important thing is that the ViewModel does not contain any code which is specific to the View. The View is allowed to do whatever it needs to do, in order to work with the underlying ViewModel.

Using Commands to bind your View to your ViewModel is convenient, because it makes for simple, easy to read, and testable XAML code; but if you have a complicated usage scenario which requires some code-behind to "convert" the View's data into something the ViewModel can consume (in this case: coordinates and CurrentEntity), then it is perfectly acceptable to use an event handler instead, and manually execute the Command binding (or even a public method on the VM, if you desire).

The idea is to make sure your code is unit-testable: and from your description, I submit that you are totally safe.

If you wanted to make your code fit strictly into a "MVVM" mold using only commands, then you could use custom Behaviors or EventTriggers to "bridge" the gap between your View and the ViewModel's Command binding.

Upvotes: 2

Related Questions