Telerik blogs

Learn about four of the .NET MAUI Community Toolkit behaviors that can make your cross-platform app development a snap!

🧠 The .NET MAUI Community Toolkit is a curated collection of reusable components thoughtfully developed by the community. It encompasses a range of elements such as animations, converters and behaviors, all designed to accelerate app development. What’s more, it ensures seamless compatibility across iOS, Android, macOS and WinUI, all thanks to the power of .NET MAUI.

In this article, we’ll dive into four fantastic behaviors from the .NET MAUI Community Toolkit that can supercharge your application. πŸš€ The best part? They’re ready to use! All you need is to understand how to implement them.

The behaviors we’ll explore are:

  • EmailValidator
  • Masked
  • IconTintColor
  • Animation

Each of these behaviors from the .NET MAUI Community Toolkit is designed to offer specific enhancements for your app.

But first, a brief pause: What exactly are behaviors? πŸ€”

Behaviors enable the addition of specific functionalities to view elements. These modular features not only enhance reusability but also streamline the unit testing process.

✍️ If you want to know more about behaviors, I invite you to check out the official documentation article.

Initial Setup

To correctly implement the behaviors, ensure that the .NET MAUI Community Toolkit is properly configured in your app. Setting it up is straightforward, as outlined in the steps below:

  1. Installation: First, make sure to install the toolkit by adding the Community.Toolkit.Maui NuGet package.

Screenshot of Community.Toolkit.Maui NuGet package 4.0.0

  1. Setup in MauiProgram.cs: After adding the NuGet package, navigate to MauiProgram.cs. Right below UseMauiApp<App>(), append:
.UseMauiCommunityToolkit()
  1. Namespace Addition: Include the toolkit namespace in your page:
xmlns:toolkit="[http://schemas.microsoft.com/dotnet/2022/maui/toolkit](http://schemas.microsoft.com/dotnet/2022/maui/toolkit)"

1. EmailValidator Behavior

This behavior detects whether the provided text is a valid email address using a regular expression. As a result, developers can easily provide visual feedback to users regarding the validity of their email. For instance, imagine an Entry where the font color turns red for an invalid email and green when it’s valid.

When paired with an InputView (like Entry or Editor), this behavior automatically sets the keyboard to Keyboard.Email, unless a different default keyboard has been specified.

We’ll begin with a hands-on code example.

Scenario

We’re designing an Entry where the font size is set to 25 and the text is dark red when the email is invalid. Conversely, for a valid email, the font size will be 30 with green text.

Creating the Styles

We’ll define styles to encapsulate the desired visual attributes for each scenario.

βž– Invalid email:

<Style x:Key="InvalidEmailStyle" TargetType="Entry">
  <Setter Property="FontSize" Value="25"/>
  <Setter Property="TextColor" Value="DarkRed"/>
</Style>

βž– Valid email:

<Style x:Key="ValidaEmailStyle" TargetType="Entry">
  <Setter Property="FontSize" Value="30"/>
  <Setter Property="TextColor" Value="Green"/>
</Style>

The Validation Properties

EmailValidator boasts several properties, with some of the most notable ones listed below:

β–ͺ InvalidStyle and ValidStyle – Receive a Style as value. These are the styles to be presented to the user when the email is invalid or valid, respectively.

β–ͺ Flags – Receives ValidationFlags as value. This enum defines how validation is managed. The values of this enumeration are:

  • ValidateOnAttaching: Triggers validation when the behavior is attached.
  • ValidateOnFocusing: Validates the input as soon as the control gains focus.
  • ValidateOnUnfocusing: Validates the input when the control loses focus.
  • ValidateOnValueChanged: Initiates validation whenever the input value changes.
  • ForceMakeValidWhenFocused: Forces the input to appear valid when focused, regardless of its actual validity.
  • None: No automatic validation is applied.

Adding the Behavior

Now, let’s add the EmailValidationBehavior to our Entry, keeping in mind the properties we discussed earlier.

<Entry>
  <Entry.Behaviors>
    <toolkit:EmailValidationBehavior
    InvalidStyle="{StaticResource InvalidEmailStyle}"
    ValidStyle="{StaticResource ValidaEmailStyle}"
    Flags="ValidateOnValueChanged" />
  </Entry.Behaviors>
</Entry>

The outcome should resemble the following:

EmailValidator Behavior Result - typing a real email address turns it green

Masked Behavior

The Masked Behavior allows users to apply an input mask for specific data entry, ensuring consistency by only accepting values that fit the given mask. This is especially useful for standardized data formats, like credit card numbers, telephone numbers and more.

We’ll begin with a hands-on code example.

Scenario

We’re setting up a mask for Dominican Republic phone numbers. Given a sample number like (800) 222-4434, the mask format will be: (XXX) XXX-XXXX.

Masked Properties

There are two properties that will help you define your mask, which are the following:

β–ͺ Mask – Receives a string as value. Specifies the mask pattern the input value should adhere to. Mandatory. There are two ways to set up this mask:

  • Directly input a string in your desired format, e.g., XXX XXX XXXX.
  • Introduce non-replaceable characters in the format. For instance, (XXX) XXX XXXX. Here, the parentheses aren’t replaced, but instead are displayed as you type in the format. To utilize this feature effectively, you should also engage the UnmaskedCharacter property.

β–ͺ UnmaskedCharacter – Indicates the character within the Mask property that will be substituted with the user’s input. The character not specified in this property remains visible to the user. Referring to our earlier example, the value for this property will be X, ensuring that parentheses are not replaced.

Adding the Behavior

Now, let’s add the MaskedBehavior to our Entry, keeping in mind the properties we discussed earlier.

<Entry Keyboard="Numeric" Placeholder="(XXX) XXX XXXX">
  <Entry.Behaviors>
    <toolkit:MaskedBehavior Mask="(XXX) XXX XXXX" UnmaskedCharacter="X" />
  </Entry.Behaviors>
</Entry>

✍️ I added the placeholder property to provide users with clearer guidance on the expected format.

The result should look like this:

MaskedBehavior - User enters a phone number in a field, and the parentheses are placed automatically

3. IconTintColor Behavior

This behavior enables image tinting. This proves invaluable when tailoring your apps for light and dark modes. Instead of needing separate icons for each mode, you can use a single icon and adjust its tint color based on your requirements.

We’ll begin with a hands-on code example.

Scenario

We’ll apply a red tint to an icon. However, in another example, this icon will switch to orange when the device is set to dark mode and turn green in light mode.

Implementation

This behavior has a singular property named TintColor, which determines the hue for the icon tint. For instance, to achieve a red-tinted icon, follow the steps below.

✍️ Keep in mind that the starting color of the icon is blue.

heart icon is red

<Image Source="heart" HeightRequest="150" WidthRequest="150">
  <Image.Behaviors>
    <toolkit:IconTintColorBehavior TintColor="Red" />
  </Image.Behaviors>
</Image>

Now, let’s play the appearance modes.

The heart icon is green on a white background. When the user changes the  appearance to dark mode, the heart appears yellow on a black background

<Image Source="heart" HeightRequest="150" WidthRequest="150">
  <Image.Behaviors>
    <toolkit:IconTintColorBehavior TintColor="{AppThemeBinding Dark=Orange, Light=green}" />
  </Image.Behaviors>
</Image>

✍️ Interested in mastering your user interface for different appearance modes? Dive into our article Managing Light and Dark Mode with .NET MAUI.

4. Animation Behavior

This is a behavior designed to animate any attached VisualElement seamlessly. While its default mode employs a TapGestureRecognizer to initiate the animation, this trigger activates upon detection of a user’s tap or click on the VisualElement, ensuring a responsive and dynamic interaction.

We’ll begin with a hands-on code example.

Scenario

Imagine an image on the screen. Upon clicking or tapping it, the image undergoes a smooth fade effect.

Adding the Behavior

Now, let’s add the AnimationBehavior to our Image:

<Image Source="dotnet_bot.png">
  <Image.Behaviors>
    <toolkit:AnimationBehavior>
      <toolkit:AnimationBehavior.AnimationType>
        <toolkit:FadeAnimation />
      </toolkit:AnimationBehavior.AnimationType>
    </toolkit:AnimationBehavior>
  </Image.Behaviors>
</Image>

The result should look like this:

MAUI logo fades on

✍️ Curious about more animation types in .NET MAUI? Dive into our article Exploring Basic Animations in .NET MAUI.

Conclusion

πŸŽ‰ And there you have it! With these straightforward steps, we’ve successfully implemented the behaviors discussed earlier.

I hope this list of helpful behaviors from .NET MAUI Community Toolkit was beneficial to you! I encourage you to implement them into your daily life and continue exploring others! πŸ’šπŸ’•

See you next time! πŸ’‍♀️

References

This article was based on the official documentation:

Use a component library in sync with .NET MAUI’s release cadence. Try Telerik UI for .NET MAUI for free.

LeomarisReyes
About the Author

Leomaris Reyes

Leomaris Reyes is a Software Engineer from the Dominican Republic, with more than 5 years of experience. A Xamarin Certified Mobile Developer, she is also the founder of  Stemelle, an entity that works with software developers, training and mentoring with a main goal of including women in Tech. Leomaris really loves learning new things! πŸ’šπŸ’• You can follow her: Twitter, LinkedIn , AskXammy and Medium.

Related Posts

Comments

Comments are disabled in preview mode.