Previous MAUI-Application-Tag MAUI-App-LifeCycle Next

Behaviors in .NET MAUI

Behaviors in .NET MAUI

Behaviors allow you to add reusable functionality to UI controls without subclassing them. They are attached to controls and can respond to events or apply logic dynamically.

Why Behaviors?

  • Encapsulate reusable UI logic.
  • Attach functionality without modifying control code.
  • Ideal for validation, animations, and event-to-command binding.

Types of Behaviors

  • Built-in Behaviors – e.g., EventToCommandBehavior.
  • Custom Behaviors – Create your own by inheriting from Behavior<T>.

Diagram

Control (e.g., Entry)
 └── Behaviors Collection
      └── Behavior
           ├── OnAttachedTo()
           └── OnDetachingFrom()
    

Example 1: Custom Behavior (Numeric Validation)

public class NumericValidationBehavior : Behavior<Entry>
{
    protected override void OnAttachedTo(Entry entry)
    {
        entry.TextChanged += OnEntryTextChanged;
        base.OnAttachedTo(entry);
    }

    protected override void OnDetachingFrom(Entry entry)
    {
        entry.TextChanged -= OnEntryTextChanged;
        base.OnDetachingFrom(entry);
    }

    void OnEntryTextChanged(object sender, TextChangedEventArgs args)
    {
        bool isValid = int.TryParse(args.NewTextValue, out _);
        ((Entry)sender).TextColor = isValid ? Colors.Black : Colors.Red;
    }
}
    

Usage in XAML:

<Entry Placeholder="Enter number">
    <Entry.Behaviors>
        <local:NumericValidationBehavior />
    </Entry.Behaviors>
</Entry>
    

Example 2: EventToCommandBehavior

EventToCommandBehavior binds an event to a command in your ViewModel, enabling MVVM-friendly event handling.

<Entry Placeholder="Type something">
    <Entry.Behaviors>
        <xct:EventToCommandBehavior
            EventName="TextChanged"
            Command="{Binding TextChangedCommand}"
            CommandParameter="{Binding Source={x:Reference MyEntry}, Path=Text}" />
    </Entry.Behaviors>
</Entry>
    

ViewModel Command:

public ICommand TextChangedCommand => new Command<string>(text =>
{
    Console.WriteLine($"Text changed: {text}");
});
    

Best Practices

  • 💡 Keep behaviors focused on one responsibility.
  • 💡 Detach event handlers in OnDetachingFrom() to avoid memory leaks.
  • 💡 Use behaviors for UI logic, not business logic.
  • 💡 Prefer EventToCommandBehavior for MVVM compliance.

Normal Behaviors vs Attached Behaviors in .NET MAUI

Behaviors in .NET MAUI allow you to add reusable functionality to UI controls. There are two main types: Normal Behaviors and Attached Behaviors.

Normal Behaviors

Normal behaviors inherit from Behavior<T> and are attached to a control via its Behaviors collection.

  • Control-specific.
  • Declared inside <Behaviors> in XAML.

Example:

<Entry Placeholder="Enter number">
    <Entry.Behaviors>
        <local:NumericValidationBehavior />
    </Entry.Behaviors>
</Entry>
    

Attached Behaviors

Attached behaviors use attached properties to apply logic declaratively without adding a Behavior object explicitly.

  • Applied using an attached property in XAML.
  • Great for global or cleaner XAML usage.

Example:

<Entry local:AttachedBehavior.IsNumeric="True" />
    

Attached Behavior Class:

public static class AttachedBehavior
{
    public static readonly BindableProperty IsNumericProperty =
        BindableProperty.CreateAttached("IsNumeric", typeof(bool), typeof(AttachedBehavior), false, propertyChanged: OnIsNumericChanged);

    public static bool GetIsNumeric(BindableObject view) => (bool)view.GetValue(IsNumericProperty);
    public static void SetIsNumeric(BindableObject view, bool value) => view.SetValue(IsNumericProperty, value);

    private static void OnIsNumericChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (bindable is Entry entry && (bool)newValue)
        {
            entry.TextChanged += (s, e) =>
            {
                bool isValid = int.TryParse(e.NewTextValue, out _);
                entry.TextColor = isValid ? Colors.Black : Colors.Red;
            };
        }
    }
}
    

Key Differences

Feature Normal Behavior Attached Behavior
How applied Inside <Behaviors> collection Using attached property in XAML
Reusability Good for specific controls Great for global or declarative usage
Complexity Easier to implement Requires attached property boilerplate

Diagram

Normal Behavior:
Control → Behaviors Collection → Behavior

Attached Behavior:
Control → Attached Property → Static Class Logic
    

Best Practices

  • 💡 Use Normal Behaviors for reusable logic tied to a specific control type.
  • 💡 Use Attached Behaviors for cleaner XAML or global application.
  • 💡 Always detach event handlers to avoid memory leaks.
Back to Index
Previous MAUI-Application-Tag MAUI-App-LifeCycle Next
*