Mobile app developers often encounter seemingly simple UI challenges that require platform-specific solutions. One such challenge is the proper alignment of button text across iOS and Android platforms in .NET MAUI applications. In this article, we'll explore how to achieve precise control over button text alignment in .NET MAUI by leveraging custom handlers.
Create a static class FormHandler
using Microsoft.Maui;
using System.Drawing;
#if IOS
using UIKit;
using Foundation;
#endif
#if ANDROID
using Microsoft.Maui.Controls.Compatibility.Platform.Android;
#endif
namespace DemoApp.Handlers;
public static class FormHandler
{
public static void AlignButtonTextToLeftBottom()
{
Microsoft.Maui.Handlers.ButtonHandler.Mapper.AppendToMapping("ButtonTextAlignmentToLeftBottom", (handler, view) =>
{
if (view is Button b && b.ClassId=="ButtonTextAlignmentToLeftBottom")
{
#if IOS
handler.PlatformView.VerticalAlignment = UIControlContentVerticalAlignment.Bottom;
handler.PlatformView.HorizontalAlignment = UIControlContentHorizontalAlignment.Left;
#elif ANDROID
handler.PlatformView.Gravity = Android.Views.GravityFlags.Left | Android.Views.GravityFlags.Bottom;
#endif
}
});
}
}
In certain scenarios you may need to apply the alignment only to a single button on your UI, if that is the case you can use the ClassId property. This way the style will be applied for only those elements with the defined ClassId, otherwise, just remove the conditional from the code above. Thanks to our friend MarcAlx for sharing this idea.
<Button ClassId="ButtonTextAlignmentToLeftBottom"/>
Register the handler
On the MauiProgram.cs file register the handler
FormHandler.AlignButtonTextToLeftBottom();
Conclusion
Custom handlers in .NET MAUI provide the flexibility needed to fine-tune platform-specific behaviors while maintaining a clean, cross-platform codebase. By implementing these solutions for button text alignment, we've not only solved an immediate visual challenge but also demonstrated the power and versatility of MAUI's handler architecture. Whether you're aiming for center-aligned text, left-justified content, or any specific style, I hope this guide will help you implement it seamlessly.
Follow me on Social:
- LinkedIn victorhugogarcia
- Bluesky vhugogarcia.bsky.social
- GitHub @vhugogarcia
- Threads @ihugo
- X @ivictorhugo
Top comments (0)