Xamarin Forms – MVVM & SQLite

In the MVVM pattern, the ViewModel is aware of the Model and the View interacts with the Model through the ViewModel. Instantiating the ViewModel in the App class allows all the various pages to interact with the single object. With that in place, although it’s not a prerequisite, I’ll move on to store contacts in a SQLite database and Views will interact with the DB through the VM.

  1. Contact Model

    Define the object in a class. This becomes the model.

  2. Get and Set Contacts

    Keeping the list in the Main Page, we can add records to it and send it to a ListView to display them.

    Add Contacts

    List Contacts

  3. Interact with Model through MVVM

    Now, rather than creating a list in the Main Page to store contacts, move it to the ViewModel which will instantiate the list and handle interactions with it. The ListViewContacts will no longer take a List<Contact> argument and instead get the list from App.vm.GetContacts();

  4. Import SQLite

    The MVVM will manage how views interact with the information in memory, but we still need a database to store data when the application is closed. Luckily, SQLite will help us with that. We need to add it to our project from NuGet, then create a db interface that defines a connection and a platform specific class that implements it. Lastly, we’ll add a couple of data attributes to the Contact model.

    Get Sqlite

  5. Create, Read and Delete

    Now the relationship between the ViewModel and the database needs to be established. Since the contact list will reside in the database, we’ll use the ViewModel to pass new contacts to it and retrieve existing contacts from it. The DB will be instantiated in App.xaml.cs to make it accessible everywhere and the VM will be called by the pages as they need it, MainPage and ListViewContacts.

    Stored data