MVVM in WPF

MVVM (M-V-VM) is software architectural Pattern. It is primarily used with WPF. Its main goal is to provide a clean separation between UI controls and UI logic.

This pattern can be used with XAML Platforms like WPF and Silverlight. So there are a lot benefits of following MVVM pattern.

Benefits of MVVM

  • All components are decoupled so they can be easily swapped with other
  • Separation of Concern
  • Moving code from behind code file gives you freedom of reusability
  • Designers can focus on the Presentation part and simultaneously developers can carry out with thier work
  • More Flexible to change UI without affecting the code
  • Simple unit testing

Three core components of MVVM :

  • Model
  • View
  • ViewModel

MVVM

How Components Interact

View knows about the ViewModel
ViewModel knows about the Model
Model does not know about the ViewModel
ViewModel does not know about the View




1. View

View is what we see on the screen. It is the thing, the user intracts with. It is created purely on XAML or with a very less coding in code-behind but that should not be contain any business logic. It is connected to ViewModel, either it have its own or of its parent and get the data through binding. A View is connected to the ViewModel by two ways – either in a code-behind file or in the XAML. Read about DataContext.

2. ViewModel

It comes inbetween the view and the Model and handles the view logic. It provides data from model to the view. So participating in Bindings, for two-way data binding the view model must raise PropertyChanged event. This can be achieved by implemented by INotifyPropertyChanged Interface. They also provide the implementation to Commands which can be triggered from the user interface by various user actions like button click etc.

3. Model

It refers as a data-centric approach(data-access layer) which holds data or information required in the application or also It acts as application’s domain model, you may have read it in other articles over the web also. By this it means that the model can provide a object-oriented approach and can contain business and validation logic, this generally kept is separate file.