Is usage of events considered bad and all UI logic should be implemented via commands when using MVVM pattern?
-
Depends on what kind of events you're referring to. Routed events are one staple of WPF MVVM. – BoltClock May 18 '11 at 21:44
-
1I use code-behind extensively in my WPF app for [communicating with the DWM API](http://stackoverflow.com/questions/5493149/how-do-i-make-a-wpf-window-movable-by-dragging-the-extended-glass-frame). One of the events I use, for example, is `Window.OnSourceInitialized` to communicate with the WPF window's Win32 handle. That's UI logic that definitely belongs in the view and its code-behind, not anywhere else, and has absolutely nothing to do with commands. – BoltClock May 18 '11 at 21:57
3 Answers
It is worth thinking about what the MVVM pattern really gives you.
- Seperation of concerns (which is true for all UI patterns)
- Unit testing of view logic, by executing the view-model without the view.
- Developer-Designer workflow, allowing designers using Blend to work on the same code.
If handling UI events in code behind doesn't prohibit the above, then there is no problem!
Personally I use commands if I can, but am not concerned if there is a little code-behind required.

- 68,894
- 15
- 164
- 232
-
2Agree completely. Not using the code-behind, not using events etc is a guideline to make you think "wait a minute. is there a more mvvm-y way to do this?" If not, then go right on. – Tim May 18 '11 at 21:56
-
I concur. Code-behind is find if its just simple view wiring that doesn't involve state or logic. – Ritch Melton May 18 '11 at 23:51
To add to ColinE's answer, events can be used, but the problem with allowing codebehind events is that it's a slippery slope. you add one thing, then you add another, and all of a sudden you create actual logic in the codebehind class. (It's even more prominent if you are working with other less experienced programmers in your team).
That's why I prefer, to almost no exceptions, to not write codebehind AT ALL. Every code that fits the codebehind without being really application-logic code can also be written within a Behavior, which makes the architecture much more strict and simple to define.
Also, Behaviors, being such a strong addition to WPF4, are by their nature very encapsulated and very reusable, so usually you're better off with a Behavior by any standard.
It depends on how event is used. I believe you are fine if you use event for UI specific effects. After all, your view defines how UI behaives, so it's even a right place to put your UI specific logic in code behind within your view.
However, your application/business logic supposed to be in the ViewModel or Model. In such case, if binding doesn't do the job and event is necessary, all event handler should do is to delegate all logic to ViewModel.

- 1,021
- 11
- 24