MSDN Documentation

MAUI Data Binding

Data binding is a powerful mechanism in .NET MAUI that simplifies the process of connecting your user interface elements to your application's data. It allows you to synchronize data between UI elements (like labels, text boxes, and buttons) and your data models, automatically updating the UI when the data changes and vice versa.

What is Data Binding?

At its core, data binding involves establishing a link between two entities: a binding source (typically a data model or view model) and a binding target (a property of a UI element). When this link is established, changes in the source automatically reflect in the target, and optionally, changes in the target can update the source.

Key Concepts

XAML Data Binding Syntax

Data binding is most commonly implemented in XAML using the {Binding} markup extension. Here's a basic example:

XAML Example: Binding a Label's Text

<Label Text="{Binding UserName}" />

In this example, the Text property of the Label is bound to a property named UserName on the binding source.

For two-way binding, you specify the mode:

XAML Example: Two-Way Binding for a Text Entry

<Entry Text="{Binding UserInput, Mode=TwoWay}" />

Here, changes in the Entry's Text will update the UserInput property in your data model, and changes to UserInput will update the Entry's text.

Implementing INotifyPropertyChanged

To ensure your UI updates when your data changes, your binding source object (typically a View Model) must implement the INotifyPropertyChanged interface. This interface defines an event, PropertyChanged, which should be raised whenever a bound property's value changes.

C# Example: Implementing INotifyPropertyChanged

public class UserViewModel : INotifyPropertyChanged
{
    private string _userName;
    public string UserName
    {
        get => _userName;
        set
        {
            if (_userName != value)
            {
                _userName = value;
                OnPropertyChanged(nameof(UserName)); // Notify UI of change
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Binding Context

The BindingContext property is crucial. It defines the default binding source for all elements within its scope (a Page, a Layout, or even a single Control). If not explicitly set, elements will inherit the BindingContext from their parent.

C# Example: Setting BindingContext

// In your Page's code-behind
public partial class MyPage : ContentPage
{
    public MyPage()
    {
        InitializeComponent();
        BindingContext = new UserViewModel(); // Set the ViewModel as BindingContext
    }
}

With this setup, the XAML control <Label Text="{Binding UserName}" /> will automatically look for the UserName property on the UserViewModel instance.

Value Converters

Sometimes, the data type or format of your source property doesn't directly match what your target property expects. Value converters allow you to transform the data during the binding process.

C# Example: A Simple Boolean to String Converter

public class BooleanToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool boolValue)
        {
            return boolValue ? "Yes" : "No";
        }
        return value; // Or handle error appropriately
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Implementation for TwoWay binding if needed
        if (value is string stringValue)
        {
            return stringValue.Equals("Yes", StringComparison.OrdinalIgnoreCase);
        }
        return false; // Default
    }
}

And in XAML:

<ContentPage.Resources>
    <local:BooleanToStringConverter x:Key="BoolConverter" />
</ContentPage.Resources>

<Label Text="{Binding IsActive, Converter={StaticResource BoolConverter}}" />
Tip: Data binding significantly reduces boilerplate code for UI updates, leading to cleaner, more maintainable applications. Embrace INotifyPropertyChanged and BindingContext to harness its full power.

Advanced Scenarios

MAUI data binding supports more complex scenarios like:

Explore the official .NET MAUI documentation for in-depth details on these advanced features and best practices.