MVVM – Introduction


MVVM – Introduction


”;


The well-ordered and perhaps the most reusable way to organize your code is to use the ”MVVM” pattern. The Model, View, ViewModel (MVVM pattern) is all about guiding you in how to organize and structure your code to write maintainable, testable and extensible applications.

Model − It simply holds the data and has nothing to do with any of the business logic.

ViewModel − It acts as the link/connection between the Model and View and makes stuff look pretty.

View − It simply holds the formatted data and essentially delegates everything to the Model.

View Model

Separated Presentation

To avoid the problems caused by putting application logic in code-behind or XAML, it”s best to use a technique known as separated presentation. We”re trying to avoid this, where we will have XAML and code-behind with the minimum required for working with user interface objects directly. User interface classes also contain code for complex interaction behaviors, application logic, and everything else as shown in the following figure on the left side.

Separated Presentation

  • With separated presentation, the user interface class is much simpler. It has the XAML of course, but the code behind does as little as is practical.

  • The application logic belongs in a separate class, which is often referred to as the model.

  • However, this is not the whole story. If you stop here, you”re likely to repeat a very common mistake that will lead you down the path of data binding insanity.

  • A lot of developers attempt to use data binding to connect elements in the XAML directly to properties in the model.

  • Now sometimes this can be okay, but often it”s not. The problem is the model is entirely concerned with matters of what the application does, and not with how the user interacts with the application.

  • The way in which you present data is often somewhat different from how it”s structured internally.

  • Moreover, most user interfaces have some state that does not belong in the application model.

  • For example, if your user interface uses a drag and drop, something needs to keep track of things like where the item being dragged is right now, how its appearance should change as it moves over possible drop targets, and how those drop targets might also change as the item is dragged over them.

  • This sort of state can get surprisingly complex, and needs to be thoroughly tested.

  • In practice, you normally want some other class sitting between the user interface and the model. This has two important roles.

    • First, it adapts your application model for a particular user interface view.

    • Second, it”s where any nontrivial interaction logic lives, and by that, I mean code required to get your user interface to behave in the way you want.

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *