views:

2497

answers:

2

Hello,

I like MVVM pattern, once you start using it, you get addicted to it.

I know that in perfect world your View code-behind is almost empty (maybe some code in constructor) and every aspect of View is being manipulated from ViewModel.

But there are times when creating new fields, properties,commands in ViewModel creates more code than implementing same thing in event handler.

At moment I stick to following rule:

If event handler code manipulates very small portion of it's view (for example button click event handler increases font of certain TextBlock that's located on the same view) then it's OK to implement logic inside event handlers. But if View needs to manipulate business logic or access resources that are outside of view, then I assign these responsibilities to ViewModel.

What do You think about my approach?

What do You try to avoid when using event handlers and ViewModel?

What best practices can You recommend when using MVVM pattern?

+8  A: 

I'd say your rule of thumb is not bad.

In my view, the core concern is "is the code view-specific, or does it address business logic?".

It is OK to have code in the view, if that code is strictly here to modify the view and not to carry out any kind of business logic. Your example of changing a font size is a prime example of code that is perfectly fine in a view (and would increase noise in a ViewModel, making it harder to understand and maintain). In essence, you already do some of that if you use triggers, so it's not that weird.

Keep in mind though, if you use unit tests, it will be very difficult to test that bit of view-logic. If you need it tested, you might be better off putting it in the viewmodel.

Denis Troller
A: 

I think I can add thing to the previous comment as well,

Instead of using event handlers, from very modest Experience, Commands give me much more flexibility in the sense that it provides an independent mechanism to respond to events/actions from different controls with the ability to check the status of the command itself.

Khaliloz