Skip to content

Learn Mobile Development

Alamgeer's Blog

Menu
  • Home
  • Privacy Policy
Menu
ObservableObject in MAUI

How to use ObservableObject in MAUI for Data Binding

Posted on January 10, 2023January 18, 2023 by Learn Mobile Development

The traditional way to implement MVVM (Model-View-ViewModel) using INotifyPropertyChanged interface but now we have a ObservableObject that provides a base implementation for INotifyPropertyChanged and INotifyPropertyChanging and this is exposing the PropertyChanged and PropertyChanging events. So In this article, I’m going to show you How to use ObservableObject in MAUI for Data Binding.

 Note : To use ObservableObject we must mark the viewmodel class as partial.

Let’s Start

In this article you will see :

  1. What is MVVM?
  2. Main features of ObservableObject?
  3. What is ObservableProperty attribute?
  4. What is RelayCommand attribute?
  5. How to invoke command when clicking on collectionview item?

1 – What is MVVM?

  • It stands for Model View ViewModel.
  • It enables the separation between View, Model and ViewModel.
    • View – It indicates the user interface where a user can interact with. (eg : xaml)
    • Model – the underlying data.
    • ViewModel – Intermediary between the View and the Model.
  • View and ViewModel are connected using BindingContext.
MVVM

2 – Main features of ObservableObject?

  • It provides the base implementation for INotifyPropertyChanged and INotifyPropertyChanging.
  • It exposes the PropertyChanged and PropertyChanging events.
  • It provides the series of SetProperty() methods that can be used for setting the property value.

3 – What is ObservableProperty attribute?

  • It allows us to generate observable properties from annotated fields.
  • It reduces boilerplate code.

Without ObservableProperty attribute :

private string _user;
public string User
{
    get => _user;
    set
      {
           _user = value;
           OnPropertyChanged();
      }
}

With ObservableProperty attribute :

[ObservableProperty]
private string user;

4 – What is RelayCommand attribute?

  • It allows us to generate relay command property for annotated methods.
  • It reduces boilerplate code.

Without RelayCommand attribute :

public class MainPageViewModel : INotifyPropertyChanged
{
     public ICommand AddUserCommand { get; set; }
     public ICommand DeleteUserCommand { get; set; }

     public MainPageViewModel()
     {
         AddUserCommand = new Command(() =>
         {
         });

         DeleteUserCommand = new Command<string>((user) =>
         {
         });   
     }
}

With RelayCommand attribute :

public partial class MainPageViewModel : ObservableObject
{
    public MainPageViewModel()
    {
    }

    [RelayCommand]
    public void AddUser()
    {
    }

    [RelayCommand]
    public void DeleteUser(string user)
    {
    }
}

I have created a sample demo project to understand better. So let’s deep dive into this.

In this sample demo i have used CommunityToolkit.Mvvm nuget package.

CommunityToolkit.MVVM

Create a MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="MAUIInvokeCommandOnListItemClickDemo.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Name="MainPageContainer">

    <Grid
        Padding="30,5"
        HorizontalOptions="Fill"
        RowDefinitions="*,Auto"
        RowSpacing="10"
        VerticalOptions="Fill">

        <CollectionView
            Grid.Row="0"
            Margin="0,30,0,0"
            ItemsSource="{Binding UserList}"
            SelectionMode="None">

            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Frame Padding="3" CornerRadius="0">
                        <StackLayout
                            Padding="10"
                            HorizontalOptions="FillAndExpand"
                            Orientation="Horizontal"
                            VerticalOptions="FillAndExpand">
                            <Label
                                x:Name="UserName"
                                HorizontalOptions="FillAndExpand"
                                Text="{Binding .}"
                                TextColor="Black" />
                            <Frame
                                Padding="7"
                                CornerRadius="15"
                                HeightRequest="30"
                                HorizontalOptions="EndAndExpand"
                                WidthRequest="30">
                                <Image Source="delete_user.png" />
                                <Frame.GestureRecognizers>
                                    <TapGestureRecognizer Command="{Binding BindingContext.DeleteUserCommand, Source={x:Reference MainPageContainer}}" CommandParameter="{Binding .}" />
                                </Frame.GestureRecognizers>
                            </Frame>
                        </StackLayout>
                    </Frame>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

        <VerticalStackLayout Grid.Row="1">

            <Entry Placeholder="Type name" Text="{Binding User}" />

            <Button
                Margin="0,10,0,0"
                Command="{Binding AddUserCommand}"
                HorizontalOptions="CenterAndExpand"
                Text="Add User" />

        </VerticalStackLayout>

    </Grid>

</ContentPage>
  • As in the above MainPage.xaml, I have taken CollectionView to show list of user and Entry/Button to add new user.
  • As you will notice, I bound the properties in the same way as we used to do it before.

MainPage.xaml.cs

namespace MAUIInvokeCommandOnListItemClickDemo;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        BindingContext = new MainPageViewModel();
    }
}

Create a MainPageViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;

namespace MAUIInvokeCommandOnListItemClickDemo
{
    public partial class MainPageViewModel : ObservableObject
    {
        [ObservableProperty]
        private ObservableCollection<string> userList;

        [ObservableProperty]
        private string user;

        public MainPageViewModel()
        {
            GetUserList();
        }

        [RelayCommand]
        public void AddUser()
        {
            Application.Current.Dispatcher.Dispatch(() =>
            {
                if (!string.IsNullOrEmpty(User))
                {
                    UserList.Add(User);
                    User = string.Empty;
                }
            });
        }

        [RelayCommand]
        public void DeleteUser(string user)
        {
            Application.Current.Dispatcher.Dispatch(() =>
            {
                if (!string.IsNullOrEmpty(user))
                {
                    UserList.Remove(user);
                }
            });
        }

        private void GetUserList()
        {
            UserList = new ObservableCollection<string>()
            {
                "User 1",
                "User 2",
                "User 3",
                "User 4",
                "User 5",
            };
        }
    }
}

5 – How to invoke command when clicking on collectionview item?

As you will see in MainPage.xaml, I have added a collection view item click event and passed the parameter to view model.

<Frame.GestureRecognizers>
  <TapGestureRecognizer Command="{Binding BindingContext.DeleteUserCommand, Source={x:Reference MainPageContainer}}" CommandParameter="{Binding .}" />
</Frame.GestureRecognizers>
  • MainPageContainer indicates the root page.

Result

That’s all for now!

You can check the full source code here.

Happy Coding! 😀 

You may also like

get device and app informations in maui

How to get Device and App Informations in MAUI

MediaElement in Xamarin Forms

How to use MediaElement in Xamarin Forms

Post Views: 337
Share article with

2 thoughts on “How to use ObservableObject in MAUI for Data Binding”

  1. net development says:
    May 22, 2023 at 12:01 PM

    I got this web page from my pal who told me concerning this website and now this time I am browsing this web
    page and reading very informative posts at this time.

    Reply
  2. LuizCP says:
    July 28, 2023 at 12:57 PM

    Thanx. Good explanation!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

I'm Alamgeer Ashraf and having 9+ years of experience in enterprises mobile application development with Xamarin Native, Xamarin Forms & .Net MAUI.

Archives

  • February 2023 (1)
  • January 2023 (9)
  • December 2022 (5)
  • November 2022 (6)

Latest Posts

  • Prevent Dark Mode in Xamarin forms
    How to Prevent Dark Mode in Xamarin formsFebruary 3, 2023
  • apply color to Images
    How to apply color to Images and Icons in MAUIJanuary 30, 2023
  • iOS Large Page Title
    How to set iOS large page title in MAUIJanuary 26, 2023
  • Change StatusBar Color
    How to change StatusBar color in MAUIJanuary 22, 2023
  • Item reordering to CollectionView
    How to apply item reordering to CollectionView GridItemsLayout in MAUIJanuary 18, 2023

Popular Posts

  • How to use CollectionView as a GridItemLayout in Xamarin Forms
  • How to use Expander in MAUI
  • Implementation Of Biometric Authentication in Xamarin Forms

Latest Comments

  1. Randyperly on How to use StateContainer in MAUIOctober 18, 2024

    very good _________________ netgame casino бездепозитный бонус

  2. SmiSew on How to use StateContainer in MAUIOctober 10, 2024

    Thanks for the post _________________ pin up casino бест

  3. StavkiTarve on How to use StateContainer in MAUIOctober 7, 2024

    interesting post _________________ слоты в 1xbet приложение

  4. Luke on How to use drag and drop gesture to CollectionView in MAUISeptember 25, 2024

    Thanks very much!

  5. Tony - Nhan Nguyen Lhoa Minh on How to apply item reordering to CollectionView GridItemsLayout in MAUIMarch 28, 2024

    That would be an amazing solution. It's easy to comprehend. Thank you very much.

Our Visitor

0 0 7 6 7 9
Users Today : 6
Users Yesterday : 9
Users Last 7 days : 29
Users Last 30 days : 170
Users This Month : 103
Total views : 13858
How to use CollectionView as a GridItemLayout in Xamarin Forms
Trending
How to use CollectionView as a GridItemLayout in Xamarin Forms

Category

  • .Net MAUI
  • MAUI Community Toolkit
  • MVVM
  • Xamarin Community Toolkit
  • Xamarin Forms

Contact Me

  • LinkedIn
      © 2025 Learn Mobile Development