Home > Sample chapters

UWP Basics

Data Binding and the Model–View–ViewModel Software Architecture Pattern

Data binding is a mechanism for binding source and target properties. Usually, the source property is a field or method from the code-behind, while the target property is a specific part of the visual layer—for example, text in a text box, an item selected in a combo box, or the state of a checkbox. The idea behind data binding is to eliminate statements responsible only for rewriting values from source to target properties. UWP offers comprehensive support for data binding through the Model–View–ViewModel (MVVM) software architectural pattern.

MVVM separates the presentation layer from the logic and data layers. This offers several advantages. Most importantly, it lets you declare UI and logic independently. By explicitly decoupling logic from presentation, you make your code reusable. It can be shared across various apps and developed independently. Additionally, this separation results in improved maintainability and testability.

The MVVM pattern has three main elements (see Figure 4-2):

  • Model This represents the application data model and contains all related logic.

  • View This defines the visual controls employed by the user to view data or enter input.

  • ViewModel This is an intermediate object, between the view and the model.

FIGURE 4-2

FIGURE 4-2 Components of the MVVM pattern.

The relationship between these components can be summarized as follows:

  • Before the view is presented to the user, it obtains data from the ViewModel through data binding.

  • The ViewModel receives data from the model through the use of dedicated methods, interfaces, or data adapters.

Every time the user performs an action on visual controls, such as typing text into a text box or selecting an item from a list, the associated target property in the ViewModel is updated. This information is subsequently propagated to the model to synchronize the application state with the data store. This scheme represents a standard interaction between the code-behind and UI but clearly separates each layer so you can easily replace or reuse specific app elements.

Related resources

There are currently no related titles.