Remove Entry and Picker borders in .NET MAUI

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://dev.to/vhugogarcia/remove-entry-and-picker-borders-in-net-maui-2pk2

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!


Create a static class FormHandler

using Microsoft.Maui;
using System.Drawing;

#if IOS
using UIKit;
using Foundation;
#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);
#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);
#elif IOS
            handler.PlatformView.BackgroundColor = UIKit.UIColor.Clear;
            handler.PlatformView.Layer.BorderWidth = 0;
            handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
#endif
        });
    }
}

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.