MVVM is a framework for making applications in WPF.
MVVM is the same as the MVC framework. It is a 3-tier architecture plus one more layer. We can do loose coupling using MVVM.
View: Write the UI in XAML. XAML is XML. XAML is a feature for making the UI.
ViewModel: It is the intermediate between a View and Server. Whenever a request is received it first passes through the ViewModel and they bring the data from the server and based on which UI is attached to the ViewModel it shows the data in the UI.
NOTE: The best part of MVVM is we can attach multiple views to a single Viewmodel and that we cannot do in Windows Forms.
Model: We will define classes that contain various properties. Basically it contains DTO.
Server-Side: It contains your Services, Business Layer and DataAccess Layer that fetches data from the database.
There are many features that MVVM gives to us. I will cover only the important parts.
Main features:
- Command
- Binding
- Mode
- Triggers
- INotify
COMMAND: Command is a feature that helps us trigger interactaction between the UI (View) and the ViewModel.
Example
For example, a ButtonClick. Here we have a command. You can also send a command parameter.
BINDING: It is a way to attach your properties.
Example
For example, in the viewmodel you have a property, ListofRecords, that you want to attach to a view, as in the following:
- <Grid ItemSource={Binding ListofRecords}/>
Whenever you get data it will show in the grid.
MODE: Mode is like how you want to communicate between View and ViewModel.
There are 4 different Modes.
- Two-way
- One-way
- Default
- One way to source
TRIGGERS
- Event Trigger
- Property Trigger
- Data Trigger
Property Trigger: A Property Trigger executes collections of setters, when the UIElements property value changes.
To create a trigger on any controls, you need to set trigger in the style of the control.
Event Trigger: An Event Trigger performs an action when the RoutedEvent of a FrameworkElement is raised.
An Event Trigger is generally used to perform some animation on a control (such as colorAnimation, doubleAnumation using KeyFrame and so on).
DataTrigger: As the name suggests, a DataTrigger applies a property value to perform an action on the data that is bound to the UIElement. The DataTrigger allows the property value to be set when the bound data matches a specified condition.
INOTIFY: The INotifyPropertyChanged interface is defined in the System.ComponentModel Class. It has an event handler called PropertyChangedEventHandler that can be used to create an event that can be used to notify the changes that occured in the properties.
For example, I had a class called MobileStore with the four properties Brand, Mode, Stock and Price. We can implement the INotifyPropertyChanged interface for that class.