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
- namespace MVVMDataBinding.Model
- {
- public class TaskModel
- {
- public string Title { get; set; }
- public int Duration { get; set; }
- public string State { get; set; }
- }
- }
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
- using MVVMDataBinding.Model;
-
- namespace MVVMDataBinding.ViewModel
- {
- public class HomeViewModels
- {
- public TaskModel TaskModel { get; set; }
- public HomeViewModels()
- {
- TaskModel = new TaskModel
- {
- Title = "Create India",
- Duration = 2,
- State = "Tamil Nadu",
- };
- }
- }
- }
Step 6
In this step, go to MainPage.xaml and open Design View. Paste the following code.
XML Code
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- xmlns:local="clr-namespace:MVVMDataBinding"
- x:Class="MVVMDataBinding.MainPage">
-
- <StackLayout VerticalOptions="Center">
- <Label Text="Title of the task"/>
- <Entry Text="{Binding TaskModel.Title}}"/>
- <Label Text="Duration of the task"/>
- <Entry Text="{Binding TaskModel.Duration}}"/>
- <Label Text="State of Country"/>
- <Entry Text="{Binding TaskModel.State}}"/>
- </StackLayout>
- </ContentPage>
Step 7
Next, open Mainpage.axml.cs Page, then add namespace MVVMDataBinding.ViewModel, and give the following C# code.
C# Code
- using MVVMDataBinding.ViewModel;
- using Xamarin.Forms;
-
- namespace MVVMDataBinding
- {
- public partial class MainPage : ContentPage
- {
- public MainPage()
- {
- InitializeComponent();
- BindingContext = new HomeViewModels();
- }
- }
- }
Step 8
Finally, Debug and Run the app to see a working MVVMDataBindding.
Finally, we have successfully created Xamarin.Forms MVVMDataBinding application.