views:

65

answers:

2

I've recently been using the MVVM light toolkit for Silverlight 4.

I really like the EventToCommand behaviour that is included, it makes life a lot easier. One thing I've been wondering about is if setting PassEventArgsToCommand="True" is bad practice as it will tie a particular RelayCommand to a particular event in the View.

E.g. If my RelayCommand is defined as:

public RelayCommand<System.Windows.Input.KeyEventArgs> myCommand

Then this can only be called by a KeyUp, KeyDown etc event.

I thought the ViewModel was to have no UI knowledge (e.g. expose a boolean converter and use a converter to change that to a Visibility), doesn't PassEventArgsToCommand break this?

A: 

One way to decouple the ViewModel from the View is to use a "broker" - something that mediates the communication between the two. I have used MVVMLight's Messenger class to implement a message broker with good results.

HTH, indyfromoz

indyfromoz
So, you would put the RelayCommand in a seperate class, not the ViewModel, and call the RelayCommand from there?
Fermin
A: 

The ViewModel is the model for the view so where you are referring to state that the view must have or data it should represent then the ViewModel should handle it.

It could be reasonable to use the Visibility enumeration to represent what part of the view should be viewed as that is about the state of the view.

As for the KeyEventArgs, this has come from an action from the user and represents some state of the command which if you need to know what key was pressed then it is a reasonable expectation of the ViewModel to handle.

If you introduce more abstractions and complexities to remove this event arg then you might have future maintenance issues provided you can unit test it with this command.

The only time I would not use Visibility or KeyEventArgs or the like would be if I wanted to use the same ViewModel for other UI technologies. If this is your case then I would create the abstraction (although in my experience this is rare and would typically involve their own ViewModels anyway).

aqwert