Data Binding in .NET MAUI with Bindable Properties

Introduction

Data binding is a powerful feature in .NET MAUI (Multi-platform App UI) that allows developers to synchronize the properties of UI elements with data sources. This synchronization ensures that when the data changes, the UI updates automatically and vice versa. In this blog post, we'll explore data binding using a BindableProperty in .NET MAUI through a simple example.

Example Overview

We'll create a basic application where a Label displays the count of students. This count will be bound to a property in the code-behind file using a BindableProperty. Here's a step-by-step guide to achieve this.

Step 1. XAML Layout

First, define the Label in your XAML file. This Label will bind to the StudentCount property in the code-behind file.

<Label Text="{Binding StudentCount}" 
       FontSize="14" 
       TextColor="Black" 
       HorizontalOptions="CenterAndExpand"/>

In this XAML code, the Text property of the Label is bound to the StudentCount property. This means that whenever StudentCount changes, the Label will automatically update its text.

Step 2. Define the Bindable Property

In the code-behind file (e.g., MainPage.xaml.cs), you need to define the StudentCount property as a BindableProperty. This makes it bindable from the XAML.

private readonly BindableProperty SCount = BindableProperty.Create(nameof(StudentCount),typeof(int),typeof(MainPage),0);

public int StudentCount
{
    get => (int)GetValue(SCount);
    set => SetValue(SCount, value);
}

Here’s a breakdown of the BindableProperty.Create method parameters:

  • nameof(StudentCount): The name of the property.
  • typeof(int): The type of the property.
  • typeof(MainPage): The type of the containing class.
  • 0: The default value of the property.

The StudentCount property is now a BindableProperty, meaning it can be used in data bindings.

Step 3. Set the Binding Context

Next, set the BindingContext of the page to this in the constructor. This makes the properties and methods of the code-behind available for data binding in the XAML.

public MainPage()
{
    InitializeComponent();

    // Set the BindingContext to this code-behind
    BindingContext = this;
}

Setting the BindingContext is crucial for the data binding to work. Without it, the XAML would not know where to look for the StudentCount property.

Step 4. Updating the Property

Now, whenever you update the StudentCount property in your code, the Label will automatically reflect the new value.

// Example of updating the StudentCount
StudentCount = StudentList.Count;

Whenever StudentList changes (e.g., adding or removing students), you should update the StudentCount property to keep the UI in sync.

Next Recommended Reading Building a login flow with .NET MAUI