Click here to Skip to main content
14,236,176 members

MVVM Databinding in Xamarin.Forms - using Fresh MVVM

Rate this:
2.33 (2 votes)
Please Sign up or sign in to vote.
2.33 (2 votes)
16 Jun 2019CPOL
An article to use Fresh MVVM for Xamarin.Forms development

Introduction

In this tutorial, we will learn how to perform MVVM approach in Xamarin.Forms using Fresh MVVM. MVVM approach is the best approach for Xamarin.Forms and WPF Applications. There are a lot of MVVM plugins or libraries like FreshMVVM, MVVMCross, Prism, etc. available to simplify MVVM implementations.

FreshMVVM

FreshMVVM is designed to perform MVVM easy and simple with Xamarin.Forms Application. It is created Michael Ridland. It has certain rules to perform MVVM Databinding. You can find the plugin from GitHub and Nuget.

Rules for FreshMVVM

It has simple rules to do MVVM. It is the first and important rule.

  • The Views (Pages) name should be ended with Page.
  • The ViewModel name should be ended with PageModel.
  • The namespace of both Page and Pagemodel should be name.
  • You don’t need to set BindingContext manually. The plugin will detect the View and ViewModel with its name.

We will start coding with FreshMVVM.

Coding Part

Steps

I have split this part into 3 steps as in the following:

  • Step 1: Creating new Xamarin.Forms Projects
  • Step 2: Setting up the plugin for Xamarin.Forms Application
  • Step 3: Implementing Fresh MVVM

Step 1

Create New Project by Selecting New -> Project -> Select Xamarin Cross Platform App and click OK.

create_project

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .NET Standard and Click OK.

choose_template

Step 2

We will start coding for Fresh MVVM. Create New Xamarin Forms Project. Open Nuget Package Manager against the solution and do search for Fresh MVVM Plugin or paste the following Nuget Installation.

Install-Package FreshMvvm -Version 2.2.3

Click Install to install this Plugin against your PCL Project or .NET standard project.

fresh_mvvm_nuget

Step 3

  • Create your XAML page (view) with name ended up with “Page”.

    fmvvm1

  • Create PageModel by create Class name ended with “PageModel” and inherited with FreshBasePageModelas shown in the below screenshot.

    fmvvm2

  • The namespace of Page and PageModel should be the same as shown in the above screenshots.
    • The Binding Properties and Command Properties are implemented the same like the normal MVVM approach.
    • To indicate the binding properties changed by using RaisePropertyChanged instead of OnPropertyChanged event in Normal MVVM.
    • The following code is used to raise the property changed.
    RaisePropertyChanged("MainPageLabel");

Set MainPage

To initialize the FreshMVVM Navigation, you should set the MainPage with FreshMVVM Navigation Container with the following code:

  • Open App.xaml.cs or App.cs and set MainPage.
    // To set MainPage for the Application
    var page = FreshPageModelResolver.ResolvePageModel<MainPageModel>();
    var basicNavContainer = new FreshNavigationContainer(page);
    MainPage = basicNavContainer;

Navigation Between Pages

FreshMVVM itself has Navigation methods to make navigation between the pages:

  • Use PushPageModel for pushing the page in the navigation stack or goto next page instead of PushAsync in normal MVVM.
    await CoreMethods.PushPageModel<SecondPageModel>();
  • It is equivalent to the following:
    Navigation.PushAsync(new SecondPage());
  • Use PopPageModel for popping the page from navigation stack instead of PopAsync in normal MVVM.
    await CoreMethods.PopPageModel();
  • It is equivalent to the following:
    Navigation.PopAsync();
  • Use PopToRoot to navigate from any page to root page instead of PopToAsync in normal MVVM.
    await CoreMethods.PopToRoot(animate:false);
  • It is equivalent to the following:
    Navigation.PopToRootAsync();

Full Code for MainPageModel

You can find the code for MainPageModel below:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using FreshMvvm;
using System;

namespace FreshMVVMSample
{
    public class MainPageModel : FreshBasePageModel
    {

        #region Default Override functions
        public override void Init(object initData)
        {
            base.Init(initData);
            MainPageLabel = "Welcome to Fresh Mvvm Tutorial!";
        }

        public override void ReverseInit(object returnedData)
        {
            base.ReverseInit(returnedData);
        }

        protected override void ViewIsAppearing(object sender, EventArgs e)
        {
            base.ViewIsAppearing(sender, e);
        }

        protected override void ViewIsDisappearing(object sender, EventArgs e)
        {
            base.ViewIsDisappearing(sender, e);
        }
        #endregion

        #region Commands
        public Command GotoSecondPageCommand
        {
            get
            {
                return new Command(async () =>
                {
                    await CoreMethods.PushPageModel<SecondPageModel>();
                });
            }
        }
        #endregion

        #region Properties
        string _mainPageLabel = string.Empty;
        public string MainPageLabel
        {
            get
            {
                return _mainPageLabel;
            }
            set
            {
                if (_mainPageLabel != value)
                {
                    _mainPageLabel = value;
                    RaisePropertyChanged(nameof(MainPageLabel));
                }
            }
        }
        #endregion
    }
}

Download Code

You can download the code from GitHub. If you have any doubts, feel free to post a comment below. If you like this article and it is useful to you, do like, share the article and star the repository on GitHub.

History

  • 16th June, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mushtaq M A
India India
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
Article
Posted 16 Jun 2019

Tagged as

Stats

1.9K views