Introduction

This article demonstrates how to create MVVM Data Binding Application using C# and XML in Xamarin.Forms.

Let’s start.

Step 1

Open Visual Studio. Go to New Project >> Installed >> Visual C# >> Cross-Platforms >> Cross-Platform App (Xamarin).

Select Cross-Platform App, then give project name and project location.

Step 2

Next, go to Solution Explorer >> Project Name (Portable), then right-click to Add >> New Folder. It opens a new dialog box; give the name to your Model.

Go to Project Name >> Model. Right-click to Add >> Class. This opens a new dialog box. Give a name to TaskModel.cs.

Step 3

Next, open Solution Explorer >> Project Name >> Model >> TaskModel.cs. Click to open C# code. Then, give the following code.

C# Code
  1. namespace MVVMDataBinding.Model
  2. {
  3. public class TaskModel
  4. {
  5. public string Title { get; set; }
  6. public int Duration { get; set; }
  7. public string State { get; set; }
  8. }
  9. }
Step 4

Similarly, add a new folder under Class page, then give the name for ViewModel and HomeViewModels.cs.

Step 5

Next, open Solution Explorer >> Project Name >> ViewModel >> HomeViewModel then click open C# code. Give the following code.

C# Code
  1. using MVVMDataBinding.Model;
  2. namespace MVVMDataBinding.ViewModel
  3. {
  4. public class HomeViewModels
  5. {
  6. public TaskModel TaskModel { get; set; }
  7. public HomeViewModels()
  8. {
  9. TaskModel = new TaskModel
  10. {
  11. Title = "Create India",
  12. Duration = 2,
  13. State = "Tamil Nadu",
  14. };
  15. }
  16. }
  17. }
Step 6

In this step, go to MainPage.xaml and open Design View. Paste the following code.

XML Code
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  4. xmlns:local="clr-namespace:MVVMDataBinding"
  5. x:Class="MVVMDataBinding.MainPage">
  6. <StackLayout VerticalOptions="Center">
  7. <Label Text="Title of the task"/>
  8. <Entry Text="{Binding TaskModel.Title}}"/>
  9. <Label Text="Duration of the task"/>
  10. <Entry Text="{Binding TaskModel.Duration}}"/>
  11. <Label Text="State of Country"/>
  12. <Entry Text="{Binding TaskModel.State}}"/>
  13. </StackLayout>
  14. </ContentPage>
Step 7

Next, open Mainpage.axml.cs Page, then add namespace MVVMDataBinding.ViewModel, and give the following C# code.

C# Code
  1. using MVVMDataBinding.ViewModel;
  2. using Xamarin.Forms;
  3. namespace MVVMDataBinding
  4. {
  5. public partial class MainPage : ContentPage
  6. {
  7. public MainPage()
  8. {
  9. InitializeComponent();
  10. BindingContext = new HomeViewModels();
  11. }
  12. }
  13. }
Step 8

Finally, Debug and Run the app to see a working MVVMDataBindding.

Finally, we have successfully created Xamarin.Forms MVVMDataBinding application.