Skip to content

Customizing Controls with Handlers

Gerald Versluis edited this page Nov 25, 2021 · 3 revisions

UI controls in .NET MAUI are rendered via handlers, lightweight classes that map properties and features to bite-sized implementations. Combine that with .NET multi-targeting and you can now succinctly augment any aspect of the native platform control.

The following examples show using compiler directives (#ifdef) to multi-target code based on platform. You can just as easily use platform-specific folders or files to organize such code like Android\Entry.cs for Entry specific customizations, or Entry.android.cs. The organization is up to you.

This code can live anywhere in your .NET MAUI project.

Example: Debug Rainbows

This would call RandomColor when setting the BackgroundColor on any view.

#if ANDROID
Microsoft.Maui.Handlers.ViewHandler.ViewMapper.AppendToMapping(nameof(IView.Background), (h, v) =>
    {
	(h.NativeView as global::Android.Views.View).SetBackgroundColor(RandomColor());
    });
#endif

Example: Remove Android Entry Underline

#if ANDROID
Microsoft.Maui.Handlers.EntryHandler.EntryMapper.AppendToMapping("NoUnderline", (h, v) =>
    {
        h.NativeView.BackgroundTintList = ColorStateList.ValueOf(Colors.Transparent.ToAndroid());
    });
#endif

Example: Accessibility Testing

#if ENABLE_TEST_CLOUD
Microsoft.Maui.Handlers.Handlers.ViewHandler.ViewMapper(nameof(IView.AutomationId), (h, v) =>
    {
        (h.NativeView as global::Android.Views.View).ContentDescription = v.AutomationId;
    });
#endif
Clone this wiki locally