MAUI Data Binding

Data binding is a powerful mechanism that establishes a connection between your user interface elements and your application data. In .NET MAUI, data binding simplifies the process of synchronizing data between your UI and your data model, reducing boilerplate code and improving maintainability.

Core Concepts of Data Binding

Data binding involves the following key components:

Types of Data Binding

.NET MAUI supports several types of data binding:

Implementing Data Binding

Data binding is typically implemented using XAML. You specify the binding using the Binding markup extension.

One-Way Binding Example

This example binds a Label's Text property to a property named MyText in the ViewModel.

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

Two-Way Binding Example

This example binds an Entry's Text property to a property named UserName in the ViewModel, allowing for bidirectional updates.

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

Binding Context

To establish a binding, the target element needs to know where to find the source. This is achieved through the BindingContext property. The BindingContext is often set on a parent element (e.g., a ContentPage or a ViewModel) and inherited by its children.

<ContentPage.BindingContext>
    <local:MyViewModel />
</ContentPage.BindingContext>

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

Data Binding Converter

Sometimes, you need to transform data before it's displayed or sent back to the source. Converters allow you to perform these transformations.

Note: To use a converter, you need to implement the IValueConverter interface and provide instances of your converter in your XAML resources.

Example of a Boolean to Visibility Converter

public class BoolToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        bool isVisible = (bool)value;
        return isVisible ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Visibility visibility = (Visibility)value;
        return visibility == Visibility.Visible;
    }
}

And in XAML:

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

<!-- ... -->

<Label Text="This is only visible when the property is true"
       IsVisible="{Binding MyBooleanProperty, Converter={StaticResource BoolToVisibilityConverter}}" />

Common Scenarios

Important: For efficient collection binding, use observable collections (e.g., ObservableCollection<T>) in your ViewModel. This allows the UI to be notified when items are added or removed from the collection.

Performance Considerations