Behaviors in .NET MAUI

Behaviors let you encapsulate reusable pieces of functionality that can be attached to visual elements without subclassing them. They are perfect for adding interactivity, validation, or platform‑specific tweaks in a clean, maintainable way.

What is a Behavior?

A Behavior<T> derives from Microsoft.Maui.Controls.Behavior<T> where T is the target view type (e.g., Entry, Button). The behavior can subscribe to events, manipulate properties, or call methods on the attached view.

public class MaxLengthBehavior : Behavior<Entry>
{
    public int MaxLength { get; set; } = 10;

    protected override void OnAttachedTo(Entry bindable)
    {
        base.OnAttachedTo(bindable);
        bindable.TextChanged += OnTextChanged;
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= OnTextChanged;
        base.OnDetachingFrom(bindable);
    }

    void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        var entry = (Entry)sender;
        if (entry.Text?.Length > MaxLength)
            entry.Text = e.OldTextValue;
    }
}

Basic Example – Adding a Tap Behavior

The snippet below adds a simple tap‑to‑toggle behavior that changes a Label's text when tapped.

public class TapToggleBehavior : Behavior<Label>
{
    bool _toggled = false;

    protected override void OnAttachedTo(Label bindable)
    {
        base.OnAttachedTo(bindable);
        var tap = new TapGestureRecognizer();
        tap.Tapped += (s, e) =>
        {
            _toggled = !_toggled;
            bindable.Text = _toggled ? "On" : "Off";
        };
        bindable.GestureRecognizers.Add(tap);
    }

    protected override void OnDetachingFrom(Label bindable)
    {
        bindable.GestureRecognizers.Clear();
        base.OnDetachingFrom(bindable);
    }
}

Using a Behavior in XAML

After creating the behavior, reference it in XAML like any other resource.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MyApp.Behaviors"
             x:Class="MyApp.MainPage">

    <ContentPage.Resources>
        <ResourceDictionary>
            <local:MaxLengthBehavior x:Key="MaxLengthBehavior" MaxLength="5"/>
        </ResourceDictionary>
    </ContentPage.Resources>

    <StackLayout Padding="20">
        <Entry Placeholder="Enter up to 5 chars">
            <Entry.Behaviors>
                <StaticResource Key="MaxLengthBehavior"/>
            </Entry.Behaviors>
        </Entry>
    </StackLayout>
</ContentPage>

Live Demo – Simulating a Simple Behavior

Hover over the box below to see a visual "behavior" in action. The effect is driven by JavaScript to illustrate how a behavior can modify UI state.

Hover me