Chapter 1: Introduction to .NETÂ MAUI and Handler Architecture
Inventory starts small: one Practice page with a heading, a line that names the platform the app is running on, a text box without a border and a button that gets a gradient background on Android and Apple devices. This chapter walks through the files behind that page. You will see where the app starts on each platform, where it registers its services, and how a handler turns a cross-platform control into a native one. Chapter 2 installs the tools, and then you build and run this same app.
What You Will Learn
Explain how a .NET MAUI handler connects a cross-platform control to a native control, and how handlers differ from Xamarin.Forms renderers
Find the shared code, the platform folders and the target framework identifiers in a single MAUI project
Read MauiProgram.cs as the place where the app registers its handlers and services before it starts
Register a custom handler with ConfigureMauiHandlers and give each native object it creates an owner
Choose between a partial class and #if branches for platform-specific code
If you have a Xamarin.Forms app, plan how to move one screen to .NET MAUI
Prerequisites
You need basic C# classes, interfaces and async/await. You don't need any tools installed yet: this chapter reads code, and Chapter 2 installs what you need to build it. Download the companion code (see About This Book) and open the Samples/Checkpoints/Chapter01/Inventory.App folder in File Explorer or any text editor.
Concept Overview
A .NET MAUI app describes its screens once, in C# or XAML, and runs them as native controls on each platform. A MAUI Entry is the cross-platform description of a text box. Its handler creates the platform's own text box: MauiAppCompatEditText, MAUI's own EditText subclass, on Android; MauiTextField, its UITextField subclass, on iOS and Mac Catalyst; and TextBox on Windows (Figure 1.1). The handler's property mapper copies values such as the text and its color to that native control, and the handler connects and disconnects its event subscriptions. Both objects exist while the page is on screen: the MAUI Entry you work with and the native control the user sees.
Figure 1.1. A MAUI Entry describes a text box once. Its handler maps property changes to the native text input on each platform and connects and disconnects event subscriptions. Managed and native objects both still exist.
Xamarin.Forms, the framework MAUI replaced, used renderers for the same job. A renderer was one large class per control and platform. A handler is smaller, and you can change one property mapping without replacing the whole class. That makes custom controls easier to write. Handlers don't by themselves make an app faster, so measure your own app before and after a move.
Inventory.App is a single project. It builds a separate app for each target framework: net11.0-android means .NET 11 plus the Android APIs, and net11.0-ios, net11.0-maccatalyst and net11.0-windows10.0.19041.0 do the same for iOS, macOS (through Mac Catalyst) and Windows. Code in the Platforms folder is compiled only for its own target. A plain net11.0 class library can hold models and tests, but it has no Android, iOS or Windows APIs, so it can't hold platform code; Chapter 3 adds one.
MauiProgram.CreateMauiApp is where the app is put together before it starts. It registers handlers and services and then calls Build. MAUI includes a dependency-injection container: you register which class to create for a type, and when a constructor asks for that type, the container creates the object and passes it in. Chapter 6 covers this in depth. A singleton registration creates one shared object the first time something asks for it. A transient registration creates a new object each time. You will register your first pages and services this way in Chapter 3.
Migrating an Existing Xamarin.Forms Screen
Skip this section if you aren't moving an app from Xamarin.Forms. List the screen's bindings, renderers, effects, third-party controls and platform services before you change anything. Move one screen into a separate MAUI project with the same data and navigation, and keep the old app buildable so you can compare the two. Replace each renderer's lifecycle code with the handler's connect and disconnect methods; renaming OnElementChanged to ConnectHandler isn't enough, because the two have different contracts. Then check one successful operation, one denied permission and one repeated visit on every target before you move the next screen. Microsoft's upgrade guide, listed in References, covers the rest of the process.
In File Explorer or a text editor, open Samples/Checkpoints/Chapter01/Inventory.App. You should see these files and folders:
Inventory.App
Inventory.App.csproj target frameworks, title and ID
App.xaml, App.xaml.cs the shared App; creates the window
AppShell.cs the Shell and its one tab
MauiProgram.cs registrations, then Build
PracticePage.cs the Practice page
Controls.cs two custom controls and their handlers
PlatformGreeting.cs shared half of a partial class
Platforms
Android Android startup and manifest
iOS iOS startup and Info.plist
MacCatalyst Mac Catalyst startup and plists
Windows Windows startup and manifests
Resources app icon and splash screen
Open Inventory.App.csproj. Its first TargetFrameworks line lists net11.0-android, net11.0-ios and net11.0-maccatalyst, and the next line adds net11.0-windows10.0.19041.0 when you build on Windows: one project, four apps. The third line lets you build one target at a time; Chapter 2 explains it.
Step 2: Trace a Custom Entry
Open Controls.cs. BorderlessEntry inherits from Entry and adds nothing; it marks the text boxes that should lose their border, so other entries keep their normal look. BorderlessEntryHandler overrides ConnectHandler once for each platform. The Android branch receives a MauiAppCompatEditText (MAUI's EditText) and clears its underline tint, the iOS and Mac Catalyst branch sets BorderStyle to none on MauiTextField, and the Windows branch sets the WinUI text box's border thickness to 0. The AddHandler line in MauiProgram.cs connects the marker control to this handler. In Chapter 2, when the app runs, the Practice page's "Borderless entry exercise" box has no border.
Inventory.App/Controls.cs
using Microsoft.Maui;
using Microsoft.Maui.Handlers;
namespace MauiInventory.App;
public sealed class BorderlessEntry : Entry
{
}
public sealed class BorderlessEntryHandler : EntryHandler
{
#if ANDROID
protected override void ConnectHandler(Microsoft.Maui.Platform.MauiAppCompatEditText view)
{
base.ConnectHandler(view);
view.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(Android.Graphics.Color.Transparent);
}
#elif IOS || MACCATALYST
protected override void ConnectHandler(Microsoft.Maui.Platform.MauiTextField view)
{
base.ConnectHandler(view);
view.BorderStyle = UIKit.UITextBorderStyle.None;
}
#elif WINDOWS
protected override void ConnectHandler(Microsoft.UI.Xaml.Controls.TextBox view)
{
base.ConnectHandler(view);
view.BorderThickness = new Microsoft.UI.Xaml.Thickness(0);
}
#endif
}
public sealed class GradientButton : Button
{
}
public sealed class GradientButtonHandler : ButtonHandler
{
#if ANDROID
private static readonly IPropertyMapper<IButton, GradientButtonHandler>
GradientMapper = new PropertyMapper<IButton, GradientButtonHandler>(
ButtonHandler.Mapper)
{
[nameof(IButton.Background)] =
(handler, button) => handler.ApplyBackground()
};
public GradientButtonHandler() : base(GradientMapper)
{
}
private Android.Graphics.Drawables.GradientDrawable? background;
protected override void ConnectHandler(Google.Android.Material.Button.MaterialButton view)
{
base.ConnectHandler(view);
background = new Android.Graphics.Drawables.GradientDrawable(
Android.Graphics.Drawables.GradientDrawable.Orientation.LeftRight,
[Android.Graphics.Color.Rgb(20, 93, 128).ToArgb(), Android.Graphics.Color.Rgb(29, 122, 83).ToArgb()]);
}
private void ApplyBackground()
{
PlatformView.BackgroundTintList = null;
PlatformView.Background = background;
}
protected override void DisconnectHandler(Google.Android.Material.Button.MaterialButton view)
{
view.Background = null;
background?.Dispose();
background = null;
base.DisconnectHandler(view);
}
#elif IOS || MACCATALYST
private CoreAnimation.CAGradientLayer? gradient;
protected override void ConnectHandler(UIKit.UIButton view)
{
base.ConnectHandler(view);
gradient = new CoreAnimation.CAGradientLayer
{
Colors = [UIKit.UIColor.FromRGB(20, 93, 128).CGColor, UIKit.UIColor.FromRGB(29, 122, 83).CGColor]
};
view.Layer.InsertSublayer(gradient, 0);
if (VirtualView is VisualElement element)
element.SizeChanged += OnSizeChanged;
UpdateFrame();
}
private void OnSizeChanged(object? sender, EventArgs e) => UpdateFrame();
private void UpdateFrame()
{
// SizeChanged fires before MAUI sizes the native button, so use the MAUI element's new size.
if (gradient is not null && VirtualView is VisualElement element && element.Width > 0 && element.Height > 0)
gradient.Frame = new CoreGraphics.CGRect(0, 0, element.Width, element.Height);
}
protected override void DisconnectHandler(UIKit.UIButton view)
{
if (VirtualView is VisualElement element)
element.SizeChanged -= OnSizeChanged;
gradient?.RemoveFromSuperLayer();
gradient?.Dispose();
gradient = null;
base.DisconnectHandler(view);
}
#endif
}
The marker controls come before their handlers. Each handler changes only its marked native view and owns its native cleanup.
Step 3: Give Native Objects an Owner
A handler that adds something to a native control must also remove it. GradientButtonHandler creates a gradient when it connects: a GradientDrawable on Android, or a CAGradientLayer plus a size-change event on iOS and Mac Catalyst.
On Android, the Background property mapper applies the drawable and clears the native button's tint. Assigning it only in ConnectHandler is too early: the normal background mapping runs afterward and can replace it. This mapper belongs to GradientButtonHandler, so ordinary buttons keep their normal background.
DisconnectHandler removes and disposes the gradient and detaches the Apple size-change event. Inside a handler, VirtualView is the MAUI control, here the GradientButton, and PlatformView is the native control it drives. It removes only its own layer, never every layer on the button.
GradientButtonHandler has no Windows branch, so on Windows it behaves like the ordinary button handler and the "Gradient handler exercise" button looks like a normal button. Run each platform you support; each one has its own implementation.
Step 4: Compare a Partial Class with #if
Controls.cs chooses platform code with #if ANDROID and similar branches inside one file. PlatformGreeting shows the other way. PlatformGreeting.cs declares a partial method, Describe, and each Platforms subfolder supplies its own PlatformGreeting.cs with that method's body. The build includes only the folder for the target it is building. If one platform's file is missing or its signature differs, the build fails. The Practice page shows the result: on Windows its second line starts with "Windows target-specific partial implementation".
Inventory.App/PlatformGreeting.cs
namespace MauiInventory.App;
public sealed partial class PlatformGreeting
{
// A non-void partial method declares accessibility and needs an implementation
// in every target compilation. This is separate from the #if handler example.
public partial string Describe();
}
namespace MauiInventory.App;
public sealed partial class PlatformGreeting
{
public partial string Describe() => "Windows target-specific partial implementation";
}
The shared partial declaration has a platform implementation. Keep the linked Android and Apple implementations in their platform folders for those builds.
Step 5: Follow Startup into the Shared App
Each platform starts the app in its own way, and each one ends up calling MauiProgram.CreateMauiApp. Open Platforms/Android/MainApplication.cs and find CreateMauiApp() => MauiProgram.CreateMauiApp(). Next to it, MainActivity.cs is the Android activity that shows the app's window; Android-only activity code, such as an OnCreate override, belongs there. The iOS and Mac Catalyst AppDelegate.cs files and the Windows Platforms/Windows/App.xaml.cs file contain the same call. From there the shared code takes over: App.xaml.cs creates the window and puts AppShell in it. AppShell is a Shell, the MAUI class that holds an app's pages, tabs and menu, and here it holds one tab, the Practice page (Figure 1.2). With a single tab, Shell draws no tab bar: on Windows you see a menu button at the top left and the page title, Practice. Shared files like these must not name an Android or Windows type unless a compile-time condition guards it.
Figure 1.2. Every platform starts in its own files and then calls MauiProgram.CreateMauiApp. From there, the shared App creates the window and AppShell shows the first page.
Inventory.App/PracticePage.cs
namespace MauiInventory.App;
public sealed class PracticePage : ContentPage
{
private readonly Label result = new()
{
Text = "Choose an exercise."
};
private readonly IServiceProvider services;
public PracticePage(IServiceProvider services)
{
this.services = services;
Title = "Practice";
var heading = new Label
{
Text = "Inventory practice",
FontSize = 24
};
SemanticProperties.SetHeadingLevel(heading, SemanticHeadingLevel.Level1);
Content = new ScrollView
{
Content = new VerticalStackLayout
{
Padding = 20,
Spacing = 12,
Children =
{
heading,
new Label
{
Text = $"{new PlatformGreeting().Describe()}. Runtime: {Environment.Version}"},
new BorderlessEntry
{
Placeholder = "Borderless entry exercise"
},
new GradientButton
{
Text = "Gradient handler exercise"
},
result
}
}
};
}
}
Inventory.App/AppShell.cs
using Microsoft.Extensions.DependencyInjection;
namespace MauiInventory.App;
public sealed class AppShell : Shell
{
public AppShell(IServiceProvider services)
{
var home = new FlyoutItem
{
Title = "Inventory",
Route = "inventory"
};
var tools = new Tab
{
Title = "Practice",
Route = "practice"
};
tools.Items.Add(new ShellContent { Title = "Chapter practice", Route = "tools", ContentTemplate = new DataTemplate(() => new PracticePage(services)) });
home.Items.Add(tools);
Items.Add(home);
}
}
namespace MauiInventory.App;
public partial class App : Application
{
private readonly AppShell shell;
public App(AppShell shell)
{
InitializeComponent();
this.shell = shell;
}
protected override Window CreateWindow(IActivationState? activationState)
{
var window = new Window(shell);
return window;
}
}
The page uses the controls already shown; AppShell supplies that page and App creates its window.
Step 6: Read the Registrations in MauiProgram
Open MauiProgram.cs, printed in the Full Example. UseMauiApp<App>() names the class that represents the app. ConfigureMauiHandlers registers two custom handlers, one for BorderlessEntry and one for GradientButton. builder.Services.AddSingleton<AppShell>() registers the shell, so the constructor in App.xaml.cs can receive it. Everything is registered before Build; after that call the list of services is fixed. Chapter 3 adds the product list's services to this same method.
Inventory.App/MauiProgram.cs
using Microsoft.Extensions.DependencyInjection;
namespace MauiInventory.App;
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder().UseMauiApp<App>();
builder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler(typeof(BorderlessEntry), typeof(BorderlessEntryHandler));
handlers.AddHandler(typeof(GradientButton), typeof(GradientButtonHandler));
});
builder.Services.AddSingleton<AppShell>();
return builder.Build();
}
}
Full Example
Your starting project is the Chapter 1 checkpoint. After Chapter 2, when your tools are installed, you can build and run it from a terminal in Samples:
$env:BookTargetFrameworks = "net11.0-windows10.0.19041.0"
dotnet run --project Checkpoints/Chapter01/Inventory.App
A window opens on the Practice page: the heading "Inventory practice", a line that starts with "Windows target-specific partial implementation", a text box with no border, the "Gradient handler exercise" button and the text "Choose an exercise." The listings below are its startup code, its two handlers and the PlatformGreeting type; the companion code contains every other file, including the platform entry points and resources.
namespace MauiInventory.App;
public sealed partial class PlatformGreeting
{
// A non-void partial method declares accessibility and needs an implementation
// in every target compilation. This is separate from the #if handler example.
public partial string Describe();
}
namespace MauiInventory.App;
public sealed partial class PlatformGreeting
{
public partial string Describe() => "Windows target-specific partial implementation";
}
Inventory.App/PracticePage.cs
namespace MauiInventory.App;
public sealed class PracticePage : ContentPage
{
private readonly Label result = new()
{
Text = "Choose an exercise."
};
private readonly IServiceProvider services;
public PracticePage(IServiceProvider services)
{
this.services = services;
Title = "Practice";
var heading = new Label
{
Text = "Inventory practice",
FontSize = 24
};
SemanticProperties.SetHeadingLevel(heading, SemanticHeadingLevel.Level1);
Content = new ScrollView
{
Content = new VerticalStackLayout
{
Padding = 20,
Spacing = 12,
Children =
{
heading,
new Label
{
Text = $"{new PlatformGreeting().Describe()}. Runtime: {Environment.Version}"},
new BorderlessEntry
{
Placeholder = "Borderless entry exercise"
},
new GradientButton
{
Text = "Gradient handler exercise"
},
result
}
}
};
}
}
Inventory.App/AppShell.cs
using Microsoft.Extensions.DependencyInjection;
namespace MauiInventory.App;
public sealed class AppShell : Shell
{
public AppShell(IServiceProvider services)
{
var home = new FlyoutItem
{
Title = "Inventory",
Route = "inventory"
};
var tools = new Tab
{
Title = "Practice",
Route = "practice"
};
tools.Items.Add(new ShellContent { Title = "Chapter practice", Route = "tools", ContentTemplate = new DataTemplate(() => new PracticePage(services)) });
home.Items.Add(tools);
Items.Add(home);
}
}
namespace MauiInventory.App;
public partial class App : Application
{
private readonly AppShell shell;
public App(AppShell shell)
{
InitializeComponent();
this.shell = shell;
}
protected override Window CreateWindow(IActivationState? activationState)
{
var window = new Window(shell);
return window;
}
}
MauiProgram wires the definitions shown in the steps, App owns the window and AppShell supplies the Practice page. The custom handlers affect only marker controls and release the native resources they create.
Common Mistakes
A correct-looking handler class has no effect if you forget its registration. Verify the selected handler and the native result.
A shared source file that names an Android class must be excluded from other targets or guarded with #if ANDROID.
Do not copy ConnectHandler signatures from an older MAUI release. The native view type is part of the method contract.
A handler must remove in DisconnectHandler what it added in ConnectHandler, and only that.
Check the Android and Apple branches of Controls.cs on those platforms; a Windows build doesn't compile them, so it can't catch their mistakes.
Performance and Production Considerations
Keep startup work short.
Register factories in MauiProgram, then open a database or contact a service when the user needs that feature. Measure cold launch separately from navigating to an already-created page. Handler customization can change accessibility, focus and native theming, so removing a border also requires a focus and contrast check. Treat changes in app size or speed as measurements of a named build and device, not as automatic benefits of selecting .NET 11. .NET 11 runs MAUI apps on CoreCLR; NativeAOT is an opt-in publishing choice, with experimental support on Android. Tuning advice written for Xamarin or Mono doesn't carry over automatically.
Summary
You can now follow startup from each platform's entry point to MauiProgram, and from a registered handler to the native control it creates. Shared source does not remove platform contracts. Chapter 2 installs the tools and runs this app.
Key Terms
Handler architecture: The .NET MAUI design in which a handler connects each cross-platform control to its native control and maps property changes to it; managed and native objects both still exist.
Host builder pattern: The startup model in MauiProgram.cs, where a builder registers services, fonts, handlers and platform behavior through chained method calls and then builds the app.
Target framework monikers (TFMs): Identifiers such as net11.0-android and net11.0-ios that name a .NET version plus a platform. A single project builds one app for each TFM it lists, and each build compiles only that platform's code.
ConfigureMauiHandlers: Extension method on MauiAppBuilder that registers custom handler mappings between cross-platform controls and their platform-specific implementations.
Single project: One MAUI project that holds the shared code, the resources and each platform's files, and builds a separate app for each target framework. A solution can still contain other projects, such as Inventory.Core.
Ahead-of-time (AOT) compilation: Compiling code to native instructions before the app runs, instead of while it runs. .NET 11 runs MAUI apps on CoreCLR, and NativeAOT is a separate opt-in publishing choice; Chapter 15 shows which compiled forms each target uses.
Mini Quiz
1. What does a handler do for a MAUI control such as Entry?
A. It draws the control itself with one rendering engine shared by every platform
B. It creates the platform's native control, maps property values to it, and connects and disconnects its event subscriptions
C. It replaces the MAUI control, so only the native control exists while the page is on screen
D. It makes the control faster than a Xamarin.Forms renderer on every platform
2. If you add Android-specific initialization in an Activity.OnCreate override, which file is the appropriate platform-specific location?
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
3. Read this Windows branch from BorderlessEntryHandler. What happens when the registered handler connects?
A. Its native text box has zero border thickness, and normal entry event wiring is retained
B. Every Windows text box in the app loses its border
C. The handler replaces the MAUI Entry instance with a native TextBox
D. The text box receives the Android gradient
4. Which TargetFrameworks entry targets .NET 11 on iOS?
A. net11.0-ios
B. ios-11.0-net
C. xamarin.ios11.0
D. net11.0;ios
5. 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
6. When implementing a handler subclass, which method is the appropriate connection hook for configuring the native view and attaching native event handlers?
A. CreatePlatformView
B. ConnectHandler
C. MapProperty
D. OnElementChanged
Answers are provided in the Answer Key at the end of the book.
Activity
Do this activity after Chapter 2, once you can run the app. From Samples, run Copy-Item MyInventory MyActivity01 -Recurse, so MyInventory stays the same as the checkpoints. In the copy's Inventory.App.csproj, change ApplicationId to com.example.myactivity01, so on a phone or emulator the copy installs as its own app instead of replacing MyInventory.
In the copy's PracticePage.cs, find the new GradientButton entry with the text "Gradient handler exercise" in the Children list. Copy the whole entry, from new GradientButton to its closing brace and comma, paste it right below, and change the copy's Text to "Second gradient".
In Controls.cs, change the two colors in the Android branch (Color.Rgb) and in the Apple branch (UIColor.FromRGB). Run the copy with dotnet run --project MyActivity01/Inventory.App, with BookTargetFrameworks set for the target you want, as in Chapter 2: net11.0-android for the emulator or net11.0-windows10.0.19041.0 for Windows.
On Android you should see both buttons with your new gradient, and their text should stay readable when you press them. On iOS or Mac Catalyst, resize the window or rotate the device: the gradient should still fill each button exactly, without spilling past its edges.
On Windows both buttons look like normal buttons, because the handler has no Windows branch; you need Android, iOS or Mac Catalyst to see the gradient. Note which platforms you ran it on, and try the others once you have them set up.
Baseline comparison: The colors are your choice, so there is no single answer. To compare with a working gradient, run dotnet run --project Activities/Chapter01 from Samples: it opens the finished app's Controls and platform page, whose "Gradient marker button" uses the same GradientButtonHandler from Samples/Inventory.App/Controls.cs. The checks are in the activity index.
The completed Activity solution is Samples/ActivitySolutions/Chapter01/Inventory.slnx. Open it in Visual Studio, select Inventory.App and your configured target, and press F5. Open Practice; compare both gradient buttons.
This second edition introduces cross-platform application development through one growing Inventory app. It assumes basic C# classes, interfaces, collections, and async/await; Xamarin experience is not required.
Follow the Visual Studio 2026 Windows path and the documented alternatives, separating shared core logic from platform UI. The book covers Android, iOS, Mac Catalyst, and Windows, with target-specific tools and device checks where required.
What you will learn
Understand MAUI application structure, handlers, XAML, and data binding.
Use MVVM, dependency injection, navigation, and lifecycle events.
Store local data in SQLite and call remote services.
Test view models and services, and integrate device capabilities.
Check accessibility, localization, performance, and release artifacts.
16 chapters include guided work, full examples, common mistakes, short quizzes with answers, and activities. Companion code is linked inside the book.
Release DateNovember 11, 2026
GenreSoftware & AI Development
ISBN979-8-90377-089-2
Read and listen on the go with the unQbd app.Get the app