Behaviors -.Net MAUI

Swetha vennapusa
3 min readFeb 24, 2023

--

.Net MAUI Behaviors allow you to enhance the functionality of a control without subclassing. Instead, the functionality is implemented in a behavior class and attached to the control as if it was part of the control itself.

.Net MAUI Behaviors are similar to Xamarin.Forms Behaviors. Behaviors enable you to code reusability across applications and help you to avoid writing code in code behind instead we can maintain code in a behavior class. They can be used to provide full functionality to controls like

Event to command behaviors

Entry Validators

Handling events raised in a control etc

There are 2 types of behaviors

  • Attached behaviors
  • .NET MAUI behaviors

Attached behaviors

Attached behaviors are static classes with one or more attached properties. An attached property is a special type of bindable property or a custom property. They are recognizable in XAML as attributes.

Let’s create an attached behavior “MaxLengthValidatorBehavior” for entry. It changes the text color to red if the characters entered exceeds max length given

     public static class MaxLengthValidatorBehavior
{
public static readonly BindableProperty AttachBehaviorProperty =
BindableProperty.CreateAttached("AttachBehavior", typeof(bool),
typeof(MaxLengthValidatorBehavior), false, propertyChanged: OnAttachBehaviorChanged);

public static bool GetAttachBehavior(BindableObject view)
{
return (bool)view.GetValue(AttachBehaviorProperty);
}

public static void SetAttachBehavior(BindableObject view, bool value)
{
view.SetValue(AttachBehaviorProperty, value);
}
public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidatorBehavior), 0);

public static int GetMaxLength(BindableObject view)
{
return (int)view.GetValue(MaxLengthProperty);
}

public static void SetMaxLength(BindableObject view, int value)
{
view.SetValue(MaxLengthProperty, value);
}

static void OnAttachBehaviorChanged(BindableObject view, object oldValue, object newValue)
{
Entry entry = view as Entry;
if (entry == null)
{
return;
}

bool attachBehavior = (bool)newValue;
if (attachBehavior)
{
entry.TextChanged += OnEntryTextChanged;
}
else
{
entry.TextChanged -= OnEntryTextChanged;
}
}

static void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
int charLength = args.NewTextValue.Length;
((Entry)sender).TextColor = charLength > GetMaxLength(sender as View)?Color.Red:Color.Black;
}
}


The below code shows how to consume the attached behavior in XAML

 <Entry Placeholder="Enter Upto 10 char"
controls:MaxLengthValidatorBehavior.AttachBehavior="true"
controls:MaxLengthValidatorBehavior.MaxLength="10"
/>

If you want to deregister behavior set controls: MaxLengthValidatorBehavior.AttachBehavior=” false”. if AttachBehavior is true then it evaluates max length based on the maxlength value provided.

.NET MAUI behaviors

.NET MAUI behaviors are created by deriving from the Behavior or Behavior<T> class. Each control in .NET MAUI has a Behavior Collection. We can add one or more behaviors

Let's create an attached behavior “MaxLengthValidatorBehavior” for entry using .Net MAUI behaviors.

 public partial class MaxLengthValidatorBehavior:Behavior<Entry>
{

public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create("MaxLength", typeof(int), typeof(MaxLengthValidatorBehavior), 0);

public int MaxLength
{
get { return (int)GetValue(MaxLengthProperty); }
set { SetValue(MaxLengthProperty, value); }
}

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


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


void OnEntryTextChanged(object sender, TextChangedEventArgs args)
{
int charLength = args.NewTextValue.Length;
((Entry)sender).TextColor = charLength > MaxLength?Color.Red:Color.Black;
}
}

The OnAttachedTo method is called immediately after the behavior is attached to a control.

The OnDetachingFrom method is called when the behavior is removed from the control

Using the Behaviors property you can add behaviors that are attached to the Control and can execute code when events of that control are raised as shown below.

 <Entry x:Name="entry" Placeholder="Enter Upto 10 char">
<Entry.Behaviors>
<controls:MaxLengthValidatorBehavior MaxLength="10"/>
</Entry.Behaviors>
</Entry>

.NET MAUI behaviors are not implicitly removed from controls when pages are popped from the navigation stack. Instead, they must be explicitly removed from prior pages going out of scope.

entry.Behaviors.Clear();

The .NET MAUI Community Toolkit provides a collection of behaviors to make developers' lives easier. We can directly use them just by adding .Net MAUI community Namespace in Xaml.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class="CommunityToolkit.Maui.Sample.Pages.Behaviors.MaxLengthReachedBehaviorPage">

<Entry Placeholder="Start typing until MaxLength is reached..."
MaxLength="50">
<Entry.Behaviors>
<toolkit:MaxLengthReachedBehavior
Command="{Binding MaxLengthReachedCommand}" />
</Entry.Behaviors>
</Entry>

</ContentPage>

For more check .NET MAUI community Behaviors.

Image of author using buy me a coffee logo

--

--