Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 42 ยท Controls and Binding

Data Binding Basics

Understand .NET MAUI data binding: BindingContext, the Binding markup extension, paths, INotifyPropertyChanged, compiled bindings with x:DataType, and a runnable stand-in of the change-notification engine.

Data binding connects a property of a control (the target) to a property of some other object (the source), so that changing one updates the other without code that copies values around. It replaces a lot of label.Text = ... lines with one declaration in XAML, and it is the foundation of the MVVM pattern you will use in the next chapter.

MAUI itself cannot run here, so the XAML is read-only. The runnable blocks are labelled C# stand-ins: they use the real INotifyPropertyChanged interface from .NET, but the binding engine is our own few lines of code.

The pieces of a binding

Every binding has four parts:

  1. A target object and a target property: for example Label.Text. The target property must be a bindable property, which all the common properties of MAUI controls are.
  2. A source object: any C# object, usually a view model or the page itself.
  3. A path to a source property: Title, Customer.Name, Items[0].
  4. A mode that decides which direction values flow (covered in Binding Modes and Converters).
XML
<Label Text="{Binding Title}" />

The markup extension {Binding Title} says: "Take the Title property of my binding context and show it in Text."

BindingContext

The source is not named in the binding. It comes from the BindingContext property, which every BindableObject has and which is inherited down the visual tree. If you set it on a page, every control on that page uses it unless a closer element sets its own.

C#
public partial class ProfilePage : ContentPage
{
    public ProfilePage()
    {
        InitializeComponent();
        BindingContext = new ProfileViewModel { Name = "Ada", Age = 36 };
    }
}
XML
<VerticalStackLayout Padding="20" Spacing="8">
    <Label Text="{Binding Name}" FontSize="24" />
    <Label Text="{Binding Age, StringFormat='Age: {0}'}" />
</VerticalStackLayout>

You can also set a context in XAML for a sub-tree, which is handy for a detail panel:

XML
<Border BindingContext="{Binding SelectedCustomer}">
    <Label Text="{Binding Email}" />
</Border>

Inside that Border, {Binding Email} means SelectedCustomer.Email of the page's context.

Paths

A path can walk through properties and indexers:

Path Meaning
{Binding Name} context.Name
{Binding Address.City} context.Address.City
{Binding Tags[0]} first item of context.Tags
{Binding .} the context object itself

If a segment is null the binding quietly shows the default (empty text, 0). When something does not appear, a typo in the path is the first suspect: the framework only logs a warning in the debug output, it does not throw.

Binding to another element

The source does not have to be the binding context. Source and x:Reference point at another control, and RelativeSource finds one by position:

XML
<Slider x:Name="volume" Minimum="0" Maximum="100" />
<Label Text="{Binding Value, Source={x:Reference volume}, StringFormat='Volume: {0:F0}'}" />

Moving the slider updates the label with no event handler. The other useful relative sources are {RelativeSource Self} (the target element itself) and {RelativeSource AncestorType={x:Type local:MyPage}} (a parent of a given type).

Change notification: INotifyPropertyChanged

Binding to a plain property reads the value once. For the UI to follow later changes, the source must announce them by implementing INotifyPropertyChanged and raising PropertyChanged in each setter:

C#
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class ProfileViewModel : INotifyPropertyChanged
{
    private string name = "";

    public string Name
    {
        get => name;
        set
        {
            if (name == value) return;
            name = value;
            OnPropertyChanged();          // CallerMemberName supplies "Name"
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

The binding subscribes to PropertyChanged; when the event arrives with the matching property name it reads the new value and updates the target. The CallerMemberName attribute lets the compiler write the name for you, which avoids typos such as OnPropertyChanged("Nmae") that silently break the binding.

The following stand-in implements a tiny binding engine around the real interface so you can watch the mechanism work. It is not how MAUI is implemented internally (MAUI uses BindableProperty), but the observable behaviour is the same.

C# Stand-in: a minimal binding engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Try removing the OnPropertyChanged() call in the setter: the label shows only the first name. That is the classic "my binding does not update" bug.

Compiled bindings with x:DataType

By default a {Binding Name} is resolved at runtime with reflection, so a typo is only found when the page runs, and the lookup costs time. Setting x:DataType on a page or an element makes the XAML compiler check the path at build time and generate fast code instead of reflection:

XML
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:ShopApp.ViewModels"
             x:Class="ShopApp.ProfilePage"
             x:DataType="vm:ProfileViewModel">

    <Label Text="{Binding Name}" />     <!-- checked while compiling -->
</ContentPage>

With compiled bindings an unknown property such as {Binding Nmae} becomes a compiler warning (or an error if you turn warnings into errors), the app starts faster, and trimming and ahead-of-time compilation work better. Newer MAUI versions also support lambda-style bindings in C# code, label.SetBinding(Label.TextProperty, static (ProfileViewModel vm) => vm.Name);, which gives the same safety without strings. When you use x:DataType inside a DataTemplate, set it on the template, because a template does not inherit the page's type.

Bindings in code

Everything you can do in XAML you can do in C#:

C#
var label = new Label();
label.SetBinding(Label.TextProperty, nameof(ProfileViewModel.Name));
label.BindingContext = viewModel;

// with a string format and fallback
label.SetBinding(Label.TextProperty,
    new Binding(nameof(ProfileViewModel.Age), stringFormat: "Age: {0}", targetNullValue: "unknown"));

FallbackValue is used when the path cannot be resolved; TargetNullValue is used when the path resolves to null.

Debugging bindings

  • Watch the Output window: binding errors are logged as Binding: 'Nmae' property not found on ....
  • Check the BindingContext is set before you expect values; it is often set after InitializeComponent().
  • Make sure the property is a public property, not a field.
  • Remember that ObservableCollection<T> is needed for add/remove notifications on lists; changing an item's property still needs INotifyPropertyChanged on the item.

Anatomy of a binding

Target A bindable property such as Label.Text
Source The BindingContext object
Path Name, Address.City, Tags[0]
Mode One-way, two-way, one-time

Change notification keeps the target in step with the source.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a {Binding Name} get its source object from, by default?

    Without Source or RelativeSource, the binding uses the nearest BindingContext, which is inherited by child elements.
  2. 2. Your view model property changes but the label does not update. What is the most likely cause?

    A binding reads the value once; later changes only reach the UI when the source raises PropertyChanged with the property name.
  3. 3. What does x:DataType enable?

    x:DataType tells the XAML compiler the type of the binding context so paths are verified at build time and reflection is avoided.
  4. 4. Which attribute lets OnPropertyChanged() fill in the property name automatically?

    CallerMemberName makes the compiler pass the name of the calling member (the setter's property) as the argument.

Summary

  • A binding links a target property to a source property found through BindingContext and a path.
  • BindingContext is inherited by child elements; Source, x:Reference and RelativeSource override it.
  • The source must implement INotifyPropertyChanged for the UI to follow changes.
  • x:DataType turns on compiled bindings: errors at build time, less reflection.
  • StringFormat, FallbackValue and TargetNullValue shape what is shown.

Next: Binding Modes and Converters