Xamarin.Forms MVVM: How to Work with SQLite DB(C# — Xaml)
We are going to develop a ContactsBook App(Android & iOS) in MVVM Architecture using Xamarin Forms then learn how to do CRUD (Create, Read, Update and Delete) operation in the SQLite database.
Xamarin.Forms
is an open-source cross-platform framework from Microsoft for building iOS
, Android
, & Windows
apps with .NET from a single shared codebase. Using Xamarin.Forms built-in pages, layouts, and controls we can build and design mobile apps from a single API that is highly extensible.
If you are a beginner in Xamarin Development, check out this article because I have explained in detail everything you need to know before starting Xamarin development.
In this article, we are going to develop a cross-platform application(ContactsBook) which runs in both iOS and Android Platforms.
By building ContactsBook App, we are going to learn about:
- How to develop a real-world application in Xamarin Forms(Android and iOS)
- What is MVVM? How to work with MVVM Architecture?
- How to work with SQLite in Xamarin.Forms
- How to do CRUD Operation in SQLite
Ready? Let’s go.
Building Real World Application In Xamarin Forms: MVVM
MVVM Architecure :
- The Model-View-ViewModel (MVVM) pattern helps to cleanly separate the business and presentation logic of an application from its user interface (UI).
- Maintaining a clean separation between application logic and the UI helps to address numerous development issues and can make an application easier to test, maintain, and evolve.
- It can also greatly improve code re-use opportunities and allows developers and UI designers to more easily collaborate when developing their respective parts of an app.
- There are three core components in the MVVM pattern: the model, the view, and the view model. Each serves a distinct purpose.

Creating a New Project on MacOS
- Open Visual Studio and Click on New button

- Choose multiplatform so that we can build projects that can run on both iOS and Android Platform.
- Select Blank Forms App and then click Next button

- Enter your project name and Organisation Identifier
- Choose the platforms that you wish to develop your Xamarin application and click Next

- Choosing the location that you wish to store your project
- Add a Git Version and .gitignore file if you need
- Add an automated UI test to the project if you need and then Click Create
Creating a New Project on Windows

- Open Visual Studio and Click on Create a new project button

- Choose Mobile App(Xamarin Forms) and then click Next button.

- Enter your project name and location where you want to store your project files and then click Create

- Choose Blank Form page and Choose the platforms(iOS and Android) you want to develop your app and then click OK button
Add Necessary packages (Eg: SQLite)

- Right-click on the Solution Folder and Choose Manage NuGet Package

- Search for sqlite-net-pcl package and Click Add Package button
- Add the SQLite package to all the 3 projects
Configure SQLite DB for Android and iOS Projects
- Create a new Folder named Persistence in All of the projects



- For Solution Project — Right-click on the ContactBook Solution folder and then choose Add -> New Folder
- For Android Project — Right-click on the ContactBook.Android Folder and then choose Add -> New Folder
- For iOS Project — Right-click on the ContactBook.iOS Folder and then choose Add -> New Folder

- Add a New Filename ISQLiteDb.cs to Folder Persistence in ContactsBook Solution Folder
- Add a New Filename SQLiteDb.cs to Folder Persistence in ContactsBook.Android Project Folder
- Add a New Filename SQLiteDb.cs to Folder Persistence in ContactsBook.iOS Project Folder
Create a Model Class
- Create a new folder named Models in ContactsBook project Solution
- Add a new file named Contact.cs which has details of contacts such as Id, first name, last name, phone, and email
Create a View Model Class :
- The MVVM architectural pattern was invented with XAML in mind. The pattern enforces a separation between three software layers — the XAML user interface called the View; the underlying data called the Model; and an intermediary between the View and the Model, called the ViewModel.
- The View and the ViewModel are often connected through data bindings defined in the XAML file.
- The BindingContext for the View is usually an instance of the ViewModel.
- By creating a View Model, this class act as an intermediary between View and Contact Model class
- Create a Base View Model Class
- In the Base View Model Class, we implement
INotifyPropertyChanged
- INotifyPropertyChanged is an interface member in System.ComponentModel Namespace. This interface is used to notify the Control that property value has changed.
- This interface is used to notify the Control that the property value has changed to the View Model.
- In BaseViewModel class, we implemented propertyChanged for generic type and extend its properties for all data types.
2. Create a ViewModel Class For Contact:
- By creating ViewModel For Contact, we provide all the necessary details need to access each contact
- By extending the BaseViewModel class, we implement
INotifyPropertyChanged
for all the contacts, when the values edited or changes then the view model will be notified of the changes.
Create an Interface For Navigation
- Navigation logic can reside in a view’s code-behind, or in a data-bound view model.
- While placing navigation logic in a view might be the simplest approach, it is not easily testable through unit tests.
- Placing navigation logic in view model classes means that the logic can be exercised through unit tests.
- In addition, the view model can then implement logic to control navigation to ensure that certain business rules are enforced.
- For example, an app might not allow the user to navigate away from a page without first ensuring that the entered data is valid.
- The Contacts app uses the navigation class to provide view model-first navigation. This class implements the interface, which is shown in the following code example:
- The class that extends the above Interface must provide all of the above methods declared. I have created and implemented the above methods in a separate class named PageService
- DisplayAlert() — Used to display alerts based on the parameters passed
- PushAsync() — Used to Navigate from One Page View to another Page View
- PopAsync() — Used to Dismiss the current Page View
Create an Interface To Do Add, Read, Edit, Delete Contact Details
- Create an interface to do CRUD Operation of contact details
- To define the methods in IContactStore, we will extend this interface and define all the methods in view model class of Page View.
- The class that extends the above Interface must provide all of the above methods declared. I have created and implemented the above methods in a separate class named SQLiteContactStore
- GetContactsAsync() — Convert contacts stored in SQLite database to List
- DeleteContact() — Delete contact from SQLite database
- AddContact() — Add contact to SQLite database
- UpdateContact() — Update the edited contact details in SQLite database
- GetContact() — Return a contact detail by using Id
Create a View Page(Add, Read, Delete Contact):
- We need to create a View Page to design the UI, So add a new File named ContactsPage
- In ContactsPage , we develop a design to Add, Read and Delete Contacts
- In this ContactsPage.xaml , I have used Interface and parameters such as
Command
,CommandParameter
andBinding
Command and CommandParameter Property
- The commanding interface provides an alternative approach to implementing commands that is much better suited to the MVVM architecture.
- The ViewModel itself can contain commands, which are methods that are executed in reaction to a specific activity in the View such as a
Button
click. - Data bindings are defined between these commands and the
Button
. - To allow a data binding between a
Button
and a ViewModel, theButton
defines two properties: Command
of type System.Windows.Input.ICommandCommandParameter
of type Object- To use the command interface, you define a data binding that targets the
Command
property of theButton
where the source is a property in the ViewModel of typeICommand
. - The ViewModel contains code associated with that
ICommand
property that is executed when the button is clicked. You can setCommandParameter
to arbitrary data to distinguish between multiple buttons if they are all bound to the sameICommand
property in the ViewModel.
The Command
and CommandParameter
properties are also defined by the following classes:
MenuItem
and hence,ToolbarItem
, which derives fromMenuItem
TextCell
and hence,ImageCell
, which derives fromTextCell
Create a View Model for ContactsPage:
- We need to create a View Model for ContactsPage, we will implement all the do all the actions and functions in View Model page Only.
- The View and the ViewModel are often connected through data bindings defined in the XAML file.
- When LoadDataCommand is triggered when view is loaded, it will call LoadData() where it will load all the contacts stored in SQLite Db.
- When SelectContactCommand() is triggered by selecting an Item in ListView, it will call SelectContact() where it will navigate to ContactDetailPage to edit the selected contact details and save the changes in SQLite DB.
- When AddContactCommand() is triggered by click on the Add button in Toolbar, it will call AddContact() where it will navigate to New page named ContactDetailPage, to add new contact details
- When DeleteContactCommand() is triggered by clicking a Menu Item in ListView, it will call DeleteContact() where it will remove the contact detail in SQlite and ListView.
- When CallContactCommand() is triggered by clicking a Menu Item in ListView, it will call CallContact() where it will make the call to using the particular contact’s mobile number.
Assigning instances of View Model to ContactsPage
- The BindingContext for the View is usually an instance of the ViewModel.
- By assigning a ContactsViewModel instances to ContactsPage.xaml.cs, every command action that triggers in ContactsPage.xaml is called in the view model
Create a New Page View(ContactsDetailPage) To Add and Edit Contact Details:
- Add a new Form named ContactsDetailPage, in ContactsDetailsPage.xaml design an UI to add and edit contact details
TableView
is a view for displaying scrollable lists of data or choices where there are rows that don't share the same template. Unlike ListView,TableView
does not have the concept of anItemsSource
, so items must be manually added as children.- Elements in a
TableView
are organized into sections. At the root of theTableView
is theTableRoot
, which is a parent to one or moreTableSection
instances. EntryCell
is useful when you need to display text data that the user can edit.EntryCell
also exposes theCompleted
event, which is fired when the user hits the 'done' button on the keyboard while editing text.SwitchCell
is the control to use for presenting and capturing an on/off ortrue
/false
state.SwitchCell
also exposes theOnChanged
event, allowing you to respond to changes in the cell's state.- When the built-in cells aren’t enough, custom cells can be used to present and capture data in a way that makes sense for your app.
- All custom cells must derive from
ViewCell
, the same base class that all of the built-in cell types use. I have created a custom cell by providingButton
inside of View Cell. - All of these properties are bindable.
Create a View Model for ContactsDetailPage:
- As I did in previous Page View, we will add a new file named ContactsDetailViewModel
- We will define all the actions and functions inside this view model only and we will achieve this by assigning this class instance in BindingContext of the ContactsDetailPage
- When SaveCommand() is triggered by a click on the Save button, it will call Save() methods which will trigger function ContactAdded or ContactUpdated based on the Id.
- Id value is zero when a new contact is added and the value of Id value won’t be zero when the contact details parameter is passed from ContactsPage.
- Based on Id value MessaginCenter will call ContactAdded or ContactUpdated by using the string(Event.ContactAdded or Event.ContactUpdated)
MessagingCenter
messages are strings. Publishers notify subscribers of a message with one of theMessagingCenter.Send
overloads.
Messaging Center
- The Xamarin.Forms
MessagingCenter
class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references. - This mechanism allows publishers and subscribers to communicate without having a reference to each other, helping to reduce dependencies between them.
- The
MessagingCenter
class provides multicast publish-subscribe functionality. - This means that there can be multiple publishers that publish a single message, and there can be multiple subscribers listening for the same message:

- Publishers send messages using the
MessagingCenter.Send
method, while subscribers listen for messages using theMessagingCenter.Subscribe
method. - In addition, subscribers can also unsubscribe from message subscriptions, if required, with the
MessagingCenter.Unsubscribe
method. - Subscribers can register to receive a message using one of the
MessagingCenter.Subscribe
overloads. The following code example shows an example of this:
- Implement the messaging center functions in ContactsPageViewModel.cs
- When Event.ContactAdded or Event.ContactUpdated is send from ContactsDetailPage, the subscriber will receive it and call the respective functions.
Assigning instances of ContactsDetailViewModel to ContactsDetailPage
- The BindingContext for the View is usually an instance of the ViewModel.
- By assigning a ContactsDetailViewModel instances to ContactsDetailPage.xaml.cs , every command action that triggers in ContactsDetailPage.xaml is called in view model.
Resources
- Find the detailed ScreenShots and project code in this Github link. You can refer to it in case you have any queries.
- The Project is Updated for Visual Studio 8.3
Conclusion
- Now you know how to work with SQLite DB in Xamarin Forms.
- Now Build and run the project, you will the screen as the below image:

I hope you found this article helpful. If you did, please don’t hesitate to clap or share this post on Twitter or your social media of choice, every share helps me to write more. If you have any queries, feel free to comment below and I’ll see what I can do. Thanks.