Building a Cross-Platform App with .NET MAUI: Populating a ListView using ObservableCollection and INotifyPropertyChanged

Introduction


In this tutorial, we will explore how to populate a `ListView` in a .NET MAUI app using the powerful combination of `ObservableCollection` and `INotifyPropertyChanged`. This approach ensures that changes to the underlying data are automatically reflected in the UI, providing a smooth and responsive user experience.


Please, support my blog by clicking on our sponsors ad!


Prerequisites

Make sure you have .NET MAUI installed, and you have set up your development environment. If not, follow the official [installation guide](https://docs.microsoft.com/en-us/dotnet/maui/get-started/installation) before proceeding.


Creating the Model

Let's start by defining a simple model class representing items in our list. Open your project and create a new class named `ListItemModel.cs`:


public class ListItemModel : INotifyPropertyChanged
{
    private string _itemName;
    public string ItemName
    {
        get { return _itemName; }
        set
        {
            if (_itemName != value)
            {
                _itemName = value;
                OnPropertyChanged(nameof(ItemName));
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}


This class implements the `INotifyPropertyChanged` interface, allowing us to notify the UI when the `ItemName` property changes.


Creating the ViewModel

Next, let's create a view model class that will manage our data. Create a class named `ListViewModel.cs`:


public class ListViewModel
{
    public ObservableCollection<ListItemModel> Items { get; } = new ObservableCollection<ListItemModel>();

    public ListViewModel()
    {
        // Initialize the list with some sample data
        Items.Add(new ListItemModel { ItemName = "Item 1" });
        Items.Add(new ListItemModel { ItemName = "Item 2" });
        Items.Add(new ListItemModel { ItemName = "Item 3" });
    }
}


Here, we use an `ObservableCollection` to hold our `ListItemModel` instances. This collection automatically notifies the UI of any changes.


Creating the UI

Now, let's build the UI to display our list. Open your `MainPage.xaml` file:


<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://schemas.microsoft.com/dotnet/2021/maui/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="YourAppName.MainPage">
    <StackLayout>
        <ListView x:Name="itemListView"
                  ItemsSource="{Binding Items}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10">
                            <Label Text="{Binding ItemName}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>


Ensure you set the `BindingContext` in your `MainPage.xaml.cs`:


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


Conclusion

By using `ObservableCollection` and `INotifyPropertyChanged`, we've created a responsive and dynamic list in our .NET MAUI app. This approach allows for efficient handling of changes in the underlying data, ensuring a seamless user experience.


Feel free to expand upon this example by adding more features and optimizing the code based on your app's requirements. Happy coding!

Comments

Popular posts from this blog

Push Notifications in .NET MAUI: A Comprehensive Guide

Explore the UI libraries available for .NET MAUI at no cost.

Push Notification using Firebase in xamarin form (Android and IOS)