Remove Entry and Picker borders in .NET MAUI

Victor Hugo Garcia - Jun 14 '23 - - Dev Community

If you are developing a .NET MAUI app that uses form elements such as entries and pickers, you might want to apply a custom design for those fields. However, by default Android & iOS make the form fields display the form elements UI following their platform design guidelines. In this post, I will show you how to remove those borders for Android & iOS using a simple custom handler and some native code. Let’s get started!

Update: This article has been updated to support .NET MAUI 8+.


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 RemoveBorders()
    {
        Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("Borderless", (handler, view) =>
        {
#if ANDROID
            handler.PlatformView.Background = null;
            handler.PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
            handler.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Colors.Transparent.ToAndroid());
#elif IOS
            handler.PlatformView.BackgroundColor = UIKit.UIColor.Clear;
            handler.PlatformView.Layer.BorderWidth = 0;
            handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
#endif
        });

        Microsoft.Maui.Handlers.PickerHandler.Mapper.AppendToMapping("Borderless", (handler, view) =>
        {
#if ANDROID
            handler.PlatformView.Background = null;
            handler.PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
            handler.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Colors.Transparent.ToAndroid());
#elif IOS
            handler.PlatformView.BackgroundColor = UIKit.UIColor.Clear;
            handler.PlatformView.Layer.BorderWidth = 0;
            handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
#endif
        });
    }
}

Enter fullscreen mode Exit fullscreen mode

On the code shared above, in addition to remove the borders, I set the background color of the form elements to transparent on both platforms, so you get the freedom to style them as needed.

Register the handler

On the MauiProgram.cs file register the handler
FormHandler.RemoveBorders();

Conclusion

In .NET MAUI it is really cool how easy you can implement a static method that allows to execute code based on each platform. Of course if you prefer to avoid the declarative conditionals you can always use the .ios.cs and .android.cs file class naming convention.

Thanks for reading! Follow me on Twitter @ivictorhugo

. . . . . . . . . . . . . . . . .
Terabox Video Player