12

In my .NET MAUI Entry, I wanted to change the Color of the Underline in an Entry in Code-Behind.

Is there a way to do this?

enter image description here

======= Edited with implementation of Answer below ======

Hint: I tried the answer below with an own BorderlessEntryControl which was derived from an Entry Control. There, at least the Placehodler-TextColor got lost. Maybe more Properties

Before

enter image description here

After

enter image description here

3

7 Answers 7

15

For MAUI .Net 8.0

handler.PlatformView.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Transparent);
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for sharing! I haven’t switched over to .NET 8 so far, but good option when I do it
Where do we put this?
App.Xaml.cs Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping(nameof(Entry), (handler, view) => { #if ANDROID handler.PlatformView.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Transparent); #endif });
it works, it removes the underline, but after doing that you won't be able to change the backgroundColor
It does remove the underline, but is there a way to change the color of underline ?
12

Using Maui .Net 8, go to Platforms -> Android -> MainApplication.cs inside MainApplication method add this

using Android.App;
using Android.Content.Res;
using Android.Runtime;

namespace CarListApp.Maui;
[Application]
public class MainApplication : MauiApplication
{
    public MainApplication(IntPtr handle, JniHandleOwnership ownership)
        : base(handle, ownership)
    {
        Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping(nameof(Entry), (handler, view) =>
        {
            if (view is Entry)
            {
                // Remove underline
                handler.PlatformView.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Transparent);

                // Change placeholder text color
                handler.PlatformView.SetHintTextColor(ColorStateList.ValueOf(Android.Graphics.Color.Red));
            }
        });
    }

    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}

In your xaml file

<VerticalStackLayout 
    Spacing="25"
    Padding="20,10"
    VerticalOptions="Center">

    <Frame Padding="0" Margin="-5,0,0,0" Grid.Column="1" HasShadow="True" 
           HorizontalOptions="FillAndExpand" MinimumWidthRequest="290">
           
        <Entry x:Name="Username" Placeholder="Enter Username" Margin="10,0" />
    </Frame>
</VerticalStackLayout>

Result

Result


To change underline color:

Go to Platforms -> Android -> Resources -> values -> In colors.xml change colorAccent to the color you want.

Comments

11

For remove the underline on the android, you can add the following code into the MauiProgram.cs:

Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping(nameof(Entry), (handler, view) =>
        {
#if ANDROID
            handler.PlatformView.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.Transparent);

#endif
        });

And on the windows platform, you can put the following code into the /Platforms/Windows/App.xaml:

<maui:MauiWinUIApplication.Resources>
        <Thickness x:Key="TextControlBorderThemeThickness">0</Thickness>
        <Thickness x:Key="TextControlBorderThemeThicknessFocused">0</Thickness>
 </maui:MauiWinUIApplication.Resources>

And there is no underline on the ios.

update 1:

Before:

enter image description here

After:

enter image description here

11 Comments

Thanks that helped a lot. I also added something for iOS: #if __ANDROID__ handler.PlatformView.SetBackgroundColor(Android.Graphics.Color.Transparent); #elif __IOS__ handler.PlatformView.BackgroundColor = UIKit.UIColor.Clear; handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None; #endif
I tried with a BorderlessEntryControl which was derived from an Entry Control and at least here the Placeholder TextColor from the standard Entry got lost (see screenshot above). Is this normal?
SetBackgroundColor becomes a problem when you also want to have different background color for entries
this is an outdated answer now and no longer works on .NET 8
For .net 8 you can check the Taras Lisniak's answer. @DeanBeckerton
|
10

in Platform for Android, needs to add the handler, looks like this:

 protected override MauiApp CreateMauiApp()
 {
     // Remove Entry control underline
     Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("NoUnderline", (h, v) =>
     {
         h.PlatformView.BackgroundTintList =
             Android.Content.Res.ColorStateList.ValueOf(Colors.Transparent.ToAndroid());
     });

     return MauiProgram.CreateMauiApp();
 }

3 Comments

this is the answer for .Net 8 maui
it works, it removes the underline, but after doing that you won't be able to change the backgroundColor
Great answer, well done
1

I have a solution where you can clip the border/underline from the Entry. We can also use negative values in the Margin to remove the excessive whitespace.

<Entry WidthRequest="200" HeightRequest="44" Margin="-4">
    <Entry.Clip>
        <RectangleGeometry Rect="4,10,192,24" />
    </Entry.Clip>
</Entry>

Then, we can reapply our own customize Border, e.g.

CroppedEntry.mp4

<Border Padding="4" HorizontalOptions="Start" StrokeShape="RoundRectangle 5">
    <Border.Triggers>
        <DataTrigger
            Binding="{Binding IsFocused, x:DataType=Entry, Source={Reference entry}}"
            TargetType="Border"
            Value="True">
            <Setter Property="Stroke" Value="Navy" />
        </DataTrigger>
    </Border.Triggers>
    <Entry
        x:Name="entry"
        HeightRequest="44"
        WidthRequest="200" 
        Margin="-4"
        HorizontalOptions="Start"
        VerticalOptions="Start" />
    <Entry.Clip>
        <RectangleGeometry Rect="4,10,192,24" />
    </Entry.Clip>
</Border>

I have an alternate solution where I put the Entry and Label inside the same Grid but set the Opacity of the Entry to 0 so that you do not see the original border and underline. The challenge there is to recreate the look of the Entry with the Label.

<!-- MaskedEntry.xaml -->
<ContentView>
    <Grid>
        <Border Padding="10">
            <!-- I set Label.Text in this snippet but it is better to set Label.FormattedText -->
            <Label
               x:DataType="Entry"
               BindingContext="{Reference entry}"
               Text="{Binding Text}" />
        </Border>
        <Entry x:Name="entry" Opacity="0" />
    </Grid>
</ContentView>

The advantage of this pattern is you have complete customization of the appearance. You can also add regex validators to prevent invalid input. In practice, I set Label.FormattedText instead of Label.Text with more sophisticated logic to support text selection and cursor positioning.

With a bit of customization you can achieve something like this:

MaskedEntry.gif

<local:MaskedEntry
    MaxLength="10"
    Placeholder="Enter a 10-digit integer"
    RegexMask="^[\d]{0,10}$"
    WidthRequest="300" />

<local:MaskedEntry
    Placeholder="Enter a license plate (format AAA999)"
    RegexMask="^([A-Za-z]{0,2}|[A-Za-z]{3}[\d]{0,3})$"
    WidthRequest="300" />

I have a functional demo in this GitHub repo: https://github.com/stephenquan/MauiMaskedEntryDemo/blob/main/MauiMaskedEntryDemo/MaskedEntry.xaml

3 Comments

So, the basic idea behind it is that you bind everything you are interested in from the Entry to property values in the ViewModel and then assign them to corresponding properties of the Label and by using Opacity="0" you are hiding the Entry? But, how would somebody then be able to enter a text?
The Entry is still there, the user is still interacting with it. All we have changed is the method of rendering. Please, no ViewModel to populate the Label. That is not correct. In the GitHub repo, I've demonstrated how to turn the above into an Entry-like reusable component. From a 3rd party developer's point of view, you can ignore the Label/Entry implementation and just used it like a normal Entry.
Thanks for the detailed explanation! That's also a great solution!
1

Using .NET 9 and Asam's answer is still the way to go, I've found. That is unless Rolly Cervantes can give us a more detailed explanation as to how to use his code, since I got an error using the provided snippet in my custom class on the AppCompatEditText line.

namespace UnderlineTestApp;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("NoUnderline", (h, v) =>
        {
            /*    Remove the underline from any IEntry visual elements on Android and IOS.  */
            #if ANDROID
                h.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Transparent);
            #endif
            #if IOS
                h.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
            #endif
        });

        Microsoft.Maui.Handlers.EditorHandler.Mapper.AppendToMapping("NoUnderline", (h, v) =>
        {
            /*    Remove the underline from any IEditor visual elements on Android and IOS. */
            #if ANDROID
                h.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Transparent);
            #endif
            #if IOS
                /*    Only reachable on iOS 15.0 or later.  */
                #pragma warning disable CA1416 // Validate platform compatibility
                    h.PlatformView.BorderStyle = UIKit.UITextViewBorderStyle.None;
                #pragma warning restore CA1416 // Validate platform compatibility
            #endif
        });

    MauiAppBuilder? builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .UseMauiCommunityToolkit()
        .ConfigureMauiHandlers(handlers =>
        {})
        .ConfigureFonts(fonts =>
        {});

        return builder.Build();
    }
}

Refs:

Comments

0

For .Net 9, it should be like this.

public class CustomEntryHandler : EntryHandler
{
    protected override void ConnectHandler(AppCompatEditText platformView)
    {
        base.ConnectHandler(platformView);
        platformView.Background = null;  // Removes the underline
    }

    protected override void DisconnectHandler(AppCompatEditText platformView)
    {
        base.DisconnectHandler(platformView);
        platformView.Background = null;
    }
}

Then add this to your MauiProgram.cs

        .ConfigureMauiHandlers(handlers =>
        {
            handlers.AddHandler<Entry, CustomEntryHandler>();
        })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.