.NET MAUI Fundamentals: Building Cross-Platform Applications with .NET 10

.NET MAUI Fundamentals: Building Cross-Platform Applications with .NET 10

13+

Build cross-platform apps with .NET 10 and MAUI. Architecture-first guidance from setup to App Store deployment.

0 followers
25 chapters
Software & AI Development
2026

$49 a year. The paperback ships free with your first year.

Buying multiple copies? Request bulk pricing.
You're viewing a limited preview. Create a free account to read free books or get Premium to unlock the entire library.

Chapter 1: Introduction to .NET MAUI and Handler Architecture

What You Will Learn

  • Explain the architectural evolution from Xamarin.Forms renderers to .NET MAUI handlers and the associated performance benefits
  • Navigate and configure the single project structure with multi-targeting framework identifiers
  • Implement the host builder pattern in MauiProgram.cs for application bootstrapping and service registration
  • Register custom handlers and platform-specific services using ConfigureMauiHandlers
  • Organize platform-specific code within the Platforms folder structure using partial classes
  • Evaluate migration strategies for existing Xamarin.Forms applications moving to .NET MAUI

Prerequisites

No additional prerequisites beyond those listed in About This Book.

Concept Overview

.NET MAUI represents a fundamental shift in cross-platform development for .NET. Unlike its predecessor Xamarin.Forms, which relied on heavyweight renderers to bridge cross-platform controls to native implementations, .NET MAUI employs a lightweight handler architecture that reduces memory overhead and improves performance.

The framework unifies Android, iOS, macOS, and Windows development within a single project structure. This eliminates the complex solution hierarchies of Xamarin.Forms, where shared code lived in one project and platform heads existed in separate projects. Instead, .NET MAUI uses multi-targeting framework identifiers to compile platform-specific code conditionally while maintaining a unified codebase.

At the heart of every .NET MAUI application lies the host builder pattern. The MauiProgram.cs file serves as the composition root, configuring services, handlers, and platform-specific behaviors before the application launches. This approach aligns with modern .NET application hosting, providing a consistent initialization model across all supported platforms.

The handler architecture decouples cross-platform controls from their native implementations more effectively than the renderer model. Each control maps to a handler that creates and manages the native platform view on demand. This lazy initialization reduces startup memory pressure and allows for more granular platform customization without inheriting heavy base classes.

.NET 10 integration brings additional performance optimizations and API unification. The runtime improvements complement MAUI's architecture, particularly in areas such as garbage collection pressure reduction and ahead-of-time compilation for mobile targets.

Migration Strategies

Teams migrating from Xamarin.Forms should evaluate application complexity and third-party dependency compatibility before beginning migration. The .NET Upgrade Assistant automates much of the mechanical conversion process, transforming project files and namespace references. However, custom renderers require manual conversion to handlers, and complex platform-specific code may need architectural refactoring.

Compatibility considerations include verifying that third-party NuGet packages support .NET 10 and .NET MAUI. Libraries relying on Xamarin.Forms-specific abstractions require updates or replacement. Begin migration by assessing the application's custom renderer count and platform-specific service implementations; applications with heavy platform customization require more migration effort than those using standard controls.

Step-by-Step Implementation

Step 1: Create a New .NET MAUI Project

Open Visual Studio and select File > New > Project. Choose the .NET MAUI App template from the list of available project types. Name the solution "MauiArchitectureDemo" and select a location for the project files. Visual Studio generates a single project containing all platform targets, shared resources, and platform-specific folders.

The generated solution contains one project instead of the multiple projects required by Xamarin.Forms. This consolidation simplifies dependency management and reduces build configuration complexity.

Step 2: Examine the Single Project Structure

The project structure organizes code into logical sections. The root contains shared code including App.xaml, App.xaml.cs, MainPage.xaml, and MainPage.xaml.cs. The Platforms folder contains subdirectories for Android, iOS, MacCatalyst, and Windows. Each platform folder houses platform-specific initialization code and native implementations.

The Resources folder centralizes fonts, images, raw assets, and application icons. This eliminates the need to duplicate resources across multiple platform projects, reducing maintenance overhead and ensuring visual consistency.

Step 3: Configure Multi-Targeting in the Project File

Open the .csproj file by double-clicking the project name in Solution Explorer. The file contains TargetFrameworks elements specifying each platform:

<PropertyGroup>
    <TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>
    <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">
        $(TargetFrameworks);net10.0-windows10.0.19041.0
    </TargetFrameworks>
</PropertyGroup>

This configuration instructs the compiler to build against .NET 10 for each specified platform. The conditional statement for Windows ensures the Windows target only builds on Windows development machines, preventing compilation errors on macOS.

Step 4: Implement the Host Builder Pattern

Open MauiProgram.cs. This file contains the CreateMauiApp method that configures the application host:

using Microsoft.Extensions.Logging;

namespace MauiArchitectureDemo;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            });

#if DEBUG
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }
}

The MauiApp.CreateBuilder method initializes the generic host. The UseMauiApp<App> extension registers the application class. ConfigureFonts handles font registration for cross-platform usage. The builder pattern allows chaining configuration methods, creating a fluent initialization sequence.

The fluent builder pattern improves code readability and discoverability through method chaining. Each configuration method returns the builder instance, allowing the compiler to enforce valid sequencing of initialization steps. However, be aware that order matters; registering handlers after calling Build() results in runtime exceptions, and certain platform-specific configurations must occur before UseMauiApp.

Step 5: Register Custom Handlers

Handlers map cross-platform controls to native implementations. To customize existing control behavior or add new capabilities, register handlers in MauiProgram.cs:

builder.ConfigureMauiHandlers(handlers =>
{
    handlers.AddHandler(typeof(BorderlessEntry), typeof(BorderlessEntryHandler));
});

This registration associates the BorderlessEntry control with its platform-specific handler implementations. The handler pattern requires implementing platform-specific versions in the Platforms folder, while the shared code references only the abstract control.

Missing handler registration results in silent failures where the default platform handler instantiates instead of your custom implementation. This produces subtle UI inconsistencies that may not surface during development if the default handler provides similar functionality. Always verify handler registration when troubleshooting platform-specific behavior discrepancies in production builds, as missing registrations often manifest as styling issues or missing functionality without throwing exceptions.

Step 6: Organize Platform-Specific Code

Platform folders contain native initialization and handler implementations. For Android, open Platforms/Android/MainActivity.cs:

using Android.App;
using Android.Content.PM;
using Android.OS;

namespace MauiArchitectureDemo;

[Activity(Theme = "@style/Maui.SplashTheme",
          MainLauncher = true,
          ConfigurationChanges = ConfigChanges.ScreenSize |
                                ConfigChanges.Orientation |
                                ConfigChanges.UiMode |
                                ConfigChanges.ScreenLayout |
                                ConfigChanges.SmallestScreenSize |
                                ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }
}

The MainActivity inherits from MauiAppCompatActivity, which provides the MAUI host container for Android.

For iOS, open Platforms/iOS/AppDelegate.cs:

using Foundation;

namespace MauiArchitectureDemo;

[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate
{
    protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}

The AppDelegate inherits from MauiUIApplicationDelegate and returns the configured MauiApp instance.

For handler implementations, create partial classes within platform folders. In Platforms/Android/Handlers/CustomEntryHandler.cs:

using Microsoft.Maui.Handlers;

namespace MauiArchitectureDemo.Handlers;

public partial class CustomEntryHandler : EntryHandler
{
    protected override void ConnectHandler(AppCompatEditText platformView)
    {
        base.ConnectHandler(platformView);

        // Android-specific customization
        platformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
    }
}

The partial class structure allows the shared project to define the handler contract while platform folders provide concrete implementations. This maintains clean separation between cross-platform abstractions and native details.

Full Example

The following example demonstrates a complete configuration combining host builder setup, custom handler registration, and platform-specific implementations. This pattern represents the standard architecture for production .NET MAUI applications targeting .NET 10.

MauiProgram.cs:

using Microsoft.Extensions.Logging;
using MauiArchitectureDemo.Handlers;

namespace MauiArchitectureDemo;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();

        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            })
            .ConfigureMauiHandlers(handlers =>
            {
                handlers.AddHandler(typeof(BorderlessEntry), typeof(BorderlessEntryHandler));
            });

        builder.Services.AddSingleton<MainViewModel>();
        builder.Services.AddTransient<MainPage>();

#if DEBUG
        builder.Logging.AddDebug();
#endif

        return builder.Build();
    }
}

BorderlessEntry.cs (Shared):

namespace MauiArchitectureDemo.Controls;

public class BorderlessEntry : Entry
{
}

Platforms/Android/Handlers/BorderlessEntryHandler.cs:

using Microsoft.Maui.Handlers;

namespace MauiArchitectureDemo.Handlers;

public class BorderlessEntryHandler : EntryHandler
{
    protected override void ConnectHandler(AppCompatEditText platformView)
    {
        base.ConnectHandler(platformView);

        platformView.Background = null;
        platformView.SetBackgroundColor(Android.Graphics.Color.Transparent);
    }
}

Platforms/iOS/Handlers/BorderlessEntryHandler.cs:

using Microsoft.Maui.Handlers;
using Microsoft.Maui.Platform;
using UIKit;

namespace MauiArchitectureDemo.Handlers;

public class BorderlessEntryHandler : EntryHandler
{
    protected override void ConnectHandler(MauiTextField platformView)
    {
        base.ConnectHandler(platformView);

        platformView.BorderStyle = UITextBorderStyle.None;
        platformView.Layer.BorderWidth = 0;
    }
}

Project file (.csproj):

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>
        <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">
            $(TargetFrameworks);net10.0-windows10.0.19041.0
        </TargetFrameworks>

        <OutputType>Exe</OutputType>
        <RootNamespace>MauiArchitectureDemo</RootNamespace>
        <UseMaui>true</UseMaui>
        <SingleProject>true</SingleProject>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
        <MauiIcon Include="Resources\AppIcon\appicon.svg"
                  ForegroundFile="Resources\AppIcon\appiconfg.svg"
                  Color="#512BD4" />
        <MauiSplashScreen Include="Resources\Splash\splash.svg"
                          Color="#512BD4"
                          BaseSize="128,128" />
        <MauiImage Include="Resources\Images\*" />
        <MauiFont Include="Resources\Fonts\*" />
        <MauiAsset Include="Resources\Raw\**"
                   LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
    </ItemGroup>

</Project>

This implementation demonstrates the handler architecture's power. The BorderlessEntry control exists as a simple class in the shared project. Platform folders contain handler implementations that remove borders using native Android and iOS APIs. The MauiProgram.cs registers the handler mapping, and the dependency injection container configures application services. This structure eliminates the heavy renderer inheritance chain required by Xamarin.Forms, reducing memory footprint and improving startup performance.

Common Mistakes

  • Confusing handlers with renderers: Developers migrating from Xamarin.Forms often attempt to inherit from ViewRenderer or implement IVisualElementRenderer. .NET MAUI uses handlers exclusively. Inherit from the specific handler base class (e.g., EntryHandler) rather than legacy renderer types. This mistake causes compilation errors and architectural mismatches.
  • Placing platform code outside the Platforms folder: Storing Android-specific code in the root project or shared folders creates compilation errors when building for iOS. Always place platform-specific implementations within the appropriate Platforms subdirectory. Use compiler directives (#if ANDROID) only for small conditional logic blocks, not entire classes.
  • Forgetting handler registration: Creating a handler class without calling ConfigureMauiHandlers in MauiProgram.cs results in the default handler being used instead of the custom implementation. Always register handlers explicitly during application startup.
  • Mixing lifecycle initialization patterns: Calling platform-specific initialization code in the shared App.xaml.cs rather than in the platform-specific MainActivity.cs or AppDelegate.cs creates abstraction leaks. Keep platform lifecycle code within the Platforms folder to maintain clean separation of concerns.
  • Incorrect target framework syntax: Using net10.0 without platform suffixes (android, ios) in TargetFrameworks causes build failures. Always specify the full framework moniker including the platform identifier.

Performance and Production Considerations

The handler architecture provides significant memory advantages over Xamarin.Forms renderers. Renderers maintained dual view hierarchies (cross-platform and native) throughout the element lifecycle. Handlers create native views only when necessary and release them aggressively when controls detach from the visual tree. This reduces peak memory usage significantly in complex list scenarios.

Startup time improves through the host builder pattern's lazy initialization. Services registered in MauiProgram.cs instantiate only when first requested (depending on lifetime configuration). Avoid registering heavy singleton services that initialize database connections or network clients during startup. Instead, defer initialization until first use to improve cold start performance.

The single project structure reduces build times by eliminating cross-project references and duplicate compilation steps. However, conditional compilation symbols (ANDROID, IOS, MACCATALYST, WINDOWS) increase complexity. Limit conditional code blocks to platform-specific implementation details rather than business logic to maintain testability.

When targeting .NET 10, enable ahead-of-time (AOT) compilation for release builds on mobile platforms. AOT reduces just-in-time compilation overhead at the cost of larger binary sizes. Profile the application using Visual Studio's performance tools to identify handler instantiation bottlenecks, particularly in CollectionView scenarios with complex data templates.

Summary

.NET MAUI's handler architecture replaces the heavyweight renderer model of Xamarin.Forms with a lightweight, performant abstraction layer. The single project structure consolidates cross-platform and platform-specific code into one solution, simplifying maintenance and resource management. The host builder pattern in MauiProgram.cs provides a familiar, consistent initialization model for configuring services, fonts, and custom handlers.

Understanding the distinction between shared code and platform-specific implementations ensures clean architectural boundaries. Handlers offer precise control over native control creation without the memory overhead of previous approaches. When migrating from Xamarin.Forms, focus on converting custom renderers to handlers and consolidating multiple project files into the unified structure.

The combination of .NET 10 runtime improvements and MAUI's architectural efficiency creates a foundation for high-performance cross-platform applications. Proper organization of platform folders, correct handler registration, and strategic use of the dependency injection container prepare applications for production deployment across Android, iOS, macOS, and Windows platforms.

Key Terms

  • Handler architecture: The lightweight abstraction layer in .NET MAUI that maps cross-platform controls to native platform views on demand, replacing the heavyweight renderer model from Xamarin.Forms.
  • Host builder pattern: The initialization model centered in MauiProgram.cs that configures services, fonts, handlers, and platform-specific behaviors using a fluent API.
  • Multi-targeting framework identifiers: The platform-specific target framework monikers (e.g., net10.0-android, net10.0-ios) that enable conditional compilation of platform-specific code within a single project.
  • ConfigureMauiHandlers: Extension method on MauiAppBuilder that registers custom handler mappings between cross-platform controls and their platform-specific implementations.
  • Single project structure: The unified project format in .NET MAUI that consolidates all platform targets, shared resources, and platform-specific code into one solution file.
  • Ahead-of-time (AOT) compilation: Build-time compilation strategy that converts managed code to native machine code before deployment, reducing startup overhead on mobile platforms.

Mini Quiz

  1. What is the primary architectural advantage of .NET MAUI handlers over Xamarin.Forms renderers?

A. Handlers support more platform-specific APIs than renderers

B. Handlers create native views on demand rather than maintaining persistent dual view hierarchies

C. Handlers require less code to implement custom controls

D. Handlers automatically register themselves without configuration

  1. Where must Android-specific lifecycle initialization code be placed to maintain proper architectural separation?

A. In the shared App.xaml.cs file using compiler directives

B. In Platforms/Android/MainActivity.cs within the single project structure

C. In a separate Android head project referenced by the solution

D. In MauiProgram.cs inside the CreateMauiApp method

  1. What is the correct method for registering a custom handler named CustomButtonHandler for a control named CustomButton?

A. AddHandler(typeof(CustomButton), typeof(CustomButtonHandler)) inside ConfigureMauiHandlers

B. RegisterHandler<CustomButton, CustomButtonHandler>() in the constructor of App.xaml.cs

C. AddTransient<CustomButtonHandler>() in the services collection

D. Create a static constructor in CustomButton that instantiates CustomButtonHandler

  1. Which TargetFrameworks entry correctly specifies .NET 10 for iOS compilation?

A. net10.0-ios

B. ios-10.0-net

C. xamarin.ios10.0

D. net10.0;ios

  1. Why should expensive resource initialization (such as database connections) be deferred rather than performed during startup in MauiProgram.cs?

A. The host builder pattern does not support synchronous initialization

B. Early initialization increases cold start time and memory pressure before the user interacts with the feature

C. Platform-specific code cannot access resources during the CreateMauiApp phase

D. Dependency injection containers automatically dispose of resources created during startup

  1. Which method should be overridden in a handler to configure the native view immediately after it is created and connected?

A. CreatePlatformView

B. ConnectHandler

C. MapProperty

D. OnElementChanged

Answers are provided in the Answer Key at the end of the book.

Activity

  • Open the MauiArchitectureDemo solution created earlier in this chapter.
  • Create a new folder named Controls in the project root.
  • Add a new class named GradientButton that inherits from Button. This class requires no additional properties for this exercise; it serves as a marker for custom handling.
  • Create a folder structure Platforms/Android/Handlers and add a new class named GradientButtonHandler.cs.
  • Implement the Android handler as a regular class inheriting from ButtonHandler. Override ConnectHandler to set a gradient background on the native Android button using Android.Graphics.Drawables.GradientDrawable.
  • Create the corresponding folder structure Platforms/iOS/Handlers and add GradientButtonHandler.cs.
  • Implement the iOS handler as a regular class inheriting from ButtonHandler. Override ConnectHandler to configure the iOS button layer with a gradient background using CoreAnimation.CAGradientLayer.
  • Open MauiProgram.cs and register the handler mapping using ConfigureMauiHandlers to associate GradientButton with GradientButtonHandler.
  • Add a GradientButton control to MainPage.xaml and verify that the custom rendering appears when deploying to both Android and iOS targets.
  • Build the solution and deploy to at least one platform to confirm the handler architecture functions correctly.

Enjoying this book?

Create a free account to leave comments, track your progress, and more!

Read and listen on the go with the unQbd app. Get the app
An unhandled error has occurred. Reload 🗙

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please reload the page.