Xamarin.Forms MVVM Pattern
Contents
When developing applications in Xamarin.Forms, the user interface is generally developed in XAML and interaction is provided with background codes. However, this causes maintenance and testing issues when the application grows and becomes complex. You can avoid these problems by setting up projects with the MVVM model.
MVVM (Model – View – ViewModel) model separates the business and presentation layers of an application from the user interface. This separation helps make testing, maintenance, and development of an application easier. Naturally, it enables designers and developers to collaborate more harmoniously.
MVVM Design Pattern
First of all, it is important to understand the components’ tasks and how they interact with each other. The MVVM pattern consists of the basic components of Model, View and ViewModel. These layers are separate from each other. The Model layer doesn’t know the ViewModel layer and the ViewModel layer doesn’t know the View layer. Thus, it is possible to develop the components independently.
MVVM (Model-View-ViewModel)
Model
Model, in short, are non-visual classes that contain data that will be used in the application.The model class is independent of the ViewModel class. Examples are Data transfer objects (DTOs), Plain Old CLR Objects (POCOs).
ViewModel
It binds data between View and Model, executes commands and reports changes, that is, it acts as a bridge. ViewModel knows the model layer but not the View layer. ViewModel makes use of the PropertyChanged event when connecting data and the ObservableCollection class for collections.
View
View is the layer on which the image of the application is presented, that is, the UI elements are located. Ideally, build the views with XAML. Thus, you will apply the Separation of Concerns principle. In Xamarin.Forms applications, the View is usually derived from the Page or ContentView class. To interact with a view item in view, such as click, selection, define a command method in the ViewModel class and connect it to the view component. I will illustrate this below with a simple example later.
Binding ViewModel to View
The ViewModel class is usually attached to the View layer declaratively and programmatically.
Binding Declaratively
Knowingly connecting is a simpler method. It is a declarative binding of the view model to the BindingContext of the view in XAML.
<ContentPage ... xmlns:local="clr-namespace:eShop">
<ContentPage.BindingContext>
<local:LoginViewModel />
</ContentPage.BindingContext>
</ContentPage>
Its simplicity is an advantage, but it connects with the default constructor of the ViewModel class, meaning it has no parameters.
Binding Programmatically
The ViewModel class connects with the BindingContext property in the xaml.cs class of the view. With this method, parameterized constructor methods of ViewModel class can be connected.
public LoginView()
{
InitializeComponent();
BindingContext = new LoginViewModel(navigationService);
}
Updating View in Response to Changes in MVVM
ViewModel and Model classes accessible by View must implement the INotifyPropertyChanged interface. This way, when the basic properties of the ViewModel or Model class change, the components in the view change. It always triggers the PropertyChanged event when the value of a property changes and its values are used by other properties. Also, never trigger the PropertyChanged event if the value of a property doesn’t change.
In the example below, BaseViewModel is implementing the INotifyPropertyChanged interface. The OnPropertyChanged method checks and reports changes.
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
Implementing Commands
Commands are examples of objects that implement the ICommand interface. Use commands to interact with UI elements in Xamarin.Forms. To add commands to the view, add command methods in the ViewModel class, then bind these methods to the view component.
Let’s show it with an example.
First, we defined a command method named ShareCommand in ViewModel class. This method will be called when clicking the PancakeView component in the view.
public ICommand ShareCommand => new Command(() => Share.RequestAsync(selectedTrack.PreviewUrl));
Then I connected the command method using the TapGestureRecognizer feature of the PancakeView component. So when I click on PancakeView, the ShareCommand method will work.
<pv:PancakeView>
<pv:PancakeView.GestureRecognizers>
<TapGestureRecognizer Command="{Binding ShareCommand}"/>
</pv:PancakeView.GestureRecognizers>
<Image Source="share.png" HeightRequest="40" WidthRequest="40"/>
</pv:PancakeView>
Advantages of MVVM Pattern
- Separation of Concerns (SoC): MVVM model positions layers independently from each other. A new model added does not break the project structure.
- MVVM allows development of separate code on each layer. Thus, Front-end and back-end developers can collaborate easily.
- Easy to maintain. For example, a change you make to the Model class does not affect the view.
- Increases testability. Since the visual interface and code are separate from each other, it is easier to test.
Disadvantages of MVVM Pattern
Contrary to its advantages, the MVVM model also has some disadvantages.
- The amount of code increases. Naturally, connecting layers increases the amount of code.
- Memory consumption increases.
Conclusion
In summary, we examined the structure and layers of the MVVM model, then connecting layers, and finally the advantages and disadvantages. Consequently, using the MVVM model in Xamarin.Forms projects facilitates maintenance, testing and sustainability. Moreover, it greatly reduces the code complexity. This is what every developer wants.
If you’re still not sure what to do, or if you got any errors, then I suggest you use the comment section below and let me know! I am here to help!
Also, share this blog post on social media and help more people learn.
Related Links
- Using SQLite With MVVM in Xamarin
- Xamarin.Forms ListView Grouping
- Visualize Your Data With SfChart in Xamarin.Forms
2 Comments