Showing posts with label MVVM. Show all posts

Introduction Welcome to our newest blog post, where we explore the vibrant realm of MVVM (Model-View-ViewModel) architecture usin...

Mastering MVVM: A Deep Dive into .NET MAUI with MVVM Toolkit Mastering MVVM: A Deep Dive into .NET MAUI with MVVM Toolkit

A blog about android developement

MVVM

Introduction

Welcome to our newest blog post, where we explore the vibrant realm of MVVM (Model-View-ViewModel) architecture using the cutting-edge MVVM Toolkit in .NET MAUI. In this comprehensive guide, we will unravel the intricacies of MVVM and demonstrate how the MVVM Toolkit in .NET MAUI empowers developers to create robust, responsive, and easily maintainable cross-platform mobile applications. Join us on this enlightening journey as we unravel the secrets of mastering MVVM in the context of .NET MAUI.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Install Plugin:

In this steps, we will see the steps to install "MVVM Toolkit" in .NET MAUI project:
  • Access NuGet Package Manager: In Visual Studio, right-click on your .NET MAUI project in the Solution Explorer. From the context menu, select "Manage NuGet Packages."
  • Search for "CommunityToolkit.Mvvm": In the NuGet Package Manager, click on the "Browse" tab. In the search bar, type "CommunityToolkit.Mvvm" and hit Enter. The package should appear in the search results.
  • Select and Install the Package: Once you find "CommunityToolkit.Mvvm" in the search results, click on it to select it. Ensure you choose the appropriate version compatible with your .NET MAUI project. Click on the "Install" button to begin the installation process.
  • Accept License Agreement: During the installation, you may be prompted to accept the license agreement. Review the terms and conditions and click on the "Accept" button to proceed.
  • Wait for Installation to Complete: Visual Studio will download and install the package along with its dependencies. This process may take a few moments, depending on your internet connection speed.
  • Verify Installation: After the installation is complete, verify that there are no error messages in the Output window. This indicates a successful installation of the package.

Implementation

View Model

  • In this step, we create a ViewModel that inherits from the ObservableObject class. This inheritance is pivotal because ObservableObject implements the INotifyPropertyChanged interface. By doing so, we gain the ability to trigger the PropertyChanged event, a vital mechanism enabling the notification of property value changes to subscribers, primarily the UI. This synchronization is fundamental for effective data binding, ensuring seamless coordination between the user interface and the underlying ViewModel.

    For example:
    public partial class ItemEntryPageModel : ObservableObject
    {
        [ObservableProperty]
        private int _id;
        [ObservableProperty]
    	private string _name;
    	[ObservableProperty]
    	private string _description;
    
        [ICommand]
    	public async void Save()
    	{
            await Application.Current.MainPage.DisplayAlert("MAUI MVVM Sample", "Item Saved Successfully", "OK");
        }
    }
  • When we use the [ObservableProperty] attribute, properties can send automatic alerts when they change. This is important for connecting data and updating the user interface (UI) when properties change. When you apply the [ObservableProperty] attribute to a property, it does a lot of necessary coding work behind the scenes. It sets up the code needed to tell other parts of the program when a property changes. This attribute saves time because you don't have to write all this code manually. For Example: "_description" & "_name" produces "Description" & "Name" respectively.
  • The [ICommand] implementation is a way to connect methods or actions in the app with what the user sees on the screen. For instance, it can create a command called SaveCommand that's linked to the Save method. This linking is crucial for making sure that when a user does something, like clicking a button, the right action happens in the app.

View

  • Finally, we will design the View, where we create the user interface using XAML. Here, we connect the UI elements to the ViewModel properties using data binding expressions.
  • This connection enables the View to show and modify task data in real-time, ensuring a dynamic and responsive user experience.
  • <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="MauiMVVM.Views.ItemEntryPage"
                 Title="Item Entry">
        <StackLayout Margin="20"
                     Spacing="10">
            <VerticalStackLayout>
                <Label Text="Name:"
                       FontSize="16"/>
                <Entry Text="{Binding Name}" 
                       Placeholder="Item Name"/>
            </VerticalStackLayout>
    
            <VerticalStackLayout>
                <Label Text="Description:"
                       FontSize="16"/>
                <Entry Text="{Binding Description}" 
                       Placeholder="Item Description"/>
            </VerticalStackLayout>
    
    
            <Button x:Name="btn_save" 
                    Text="Save"
                    Command="{Binding SaveCommand}"/>
        </StackLayout>
    </ContentPage>
  • In .NET MAUI, data binding makes sure that data stays in sync between the ViewModel and the View without manual intervention.
  • For instance, we can link a task's title in the ViewModel to a label in the View. When the title changes, it instantly updates in the UI.
  • This automatic synchronization simplifies UI updates and eliminates the need for handling events manually.

Wire-up View and View Model

  • The created view and view model should be added in MauiProgram.cs like below.
    var builder = MauiApp.CreateBuilder();
    		builder
    			.UseMauiApp<App>()
    			.ConfigureFonts(fonts =>
    			{
    				fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
    				fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
    			});
    
    #if DEBUG
    		builder.Logging.AddDebug();
    #endif
            builder.Services.AddTransient<ItemEntryPage>();
            builder.Services.AddTransient<ItemEntryPageModel>();
    
            return builder.Build();

Full Code:

Demo

Download Code:

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

References

To learn more about Data binding and MVVM

Introduction: In this tutorial, we will learn how to perform MVVM approach in Xamarin.Forms using Fresh MVVM. MVVM approach is the best...

MVVM Databinding in Xamarin.Forms using Fresh MVVM MVVM Databinding in Xamarin.Forms using Fresh MVVM

A blog about android developement

MVVM


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 Fresh MVVM.

Coding Part:

Steps:
I have split this part into 3 steps as in the following.
  1. Creating new Xamarin.Forms Projects.
  2. Setting up the plugin for Xamarin.Forms Application.
  3. Implementing Fresh MVVM.

Step 1: Creating new Xamarin.Forms Projects

Create New Project by Selecting New -> Project -> Select Xamarin Cross Platform App and Click OK.
Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.

Step 2: Setting up the plugin for Xamarin.Forms Application

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.

Step 3: Implementing Fresh MVVM.

  1. Create your XAML page (view) with name ended up with “Page”.
  2. Create PageModel by create Class name ended with “PageModel” and inherited with “FreshBasePageModel” as shown below screenshot.
  3. The namespace of Page and PageModel should be same as shown in the above screenshots. – The Binding Properties and Command Properties are implemented same as like 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");
  4. 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. 
    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.
    1. Use PushPageModel for pushing the page in the navigation stack or goto next page instead of PushAsync in normal MVVM.
      await CoreMethods.PushPageModel();
      It is equivalent to the following
      Navigation.PushAsync(new SecondPage());
    2. 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();
    3. 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
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 doubt, feel free to post comment. If you like this article and is useful to you, do like, share the article & star the repository on GitHub.