Prism + MVVM + WPF Limitations, Code Behind & Best Practices?

Topics: Prism v4 - WPF 4
Sep 6, 2012 at 1:26 AM

We have a WPF application written in C# using Prism 4 and MVVM. Our team is having a hard time trying to determine what can go in the View Code Behind and what cannot. In the context of Best Practices and writing testable code please comment on how to address the inherit limitations of the MVVM pattern (using Prism). There are all sorts of techniques from giving the ViewModel access to the View via Interface to raising events from the ViewModel that are wired to from within the View. Are any of these suggestions okay? I do realize that in some scenarios we could write additional code creating dependency properties, but this feels like we have to spend time creating and eventually maintaining the pattern faculties and not focusing on our application.

Developer
Sep 6, 2012 at 6:46 PM

Hi,

Regarding how to determine what code must be placed in View and View Model classes, as mentioned in the documentation, sometimes this may not be so obvious and as a general rule this could be considered:

Anything concerned with the specific visual appearance of the UI on the screen and that could be re-styled later (even if you are not currently planning to re-style it) should go into the view; anything that is important to the logical behavior of the application should go into the view model. In addition, because the view model should have no explicit knowledge of the specific visual elements in the view, code to programmatically manipulate visual elements within the view should reside in the view's code-behind or be encapsulated in a behavior.Similarly, code to retrieve or manipulate data items that are to be displayed in the view through data binding should reside in the view model.

Also, particularly, I found the following post from Glenn Block (which discusses this topic) interesting:

On the other hand, regarding the interaction between these classes, as far as I know the recommended approaches are to take benefit of:

  • Data bindings (to Change the View, by setting a Property in the View Model)
  • Commands (for the View to Execute Code)
  • Data validation interfaces (to perform data validation and to signal any data validation errors to the view)
  • Behaviors (often used to Implement Interaction Users Experience)

For more information about this approaches, and how to implement them using Prism, I recommend you to check the following chapters of the documentation:

I hope you find this handy,

Agustin Adami
http://blogs.southworks.net/aadami