Mobile .NET MAUI
Purpose
Guide for building cross-platform mobile apps with .NET MAUI using MVVM, Shell navigation, and platform-specific customization.
Agent Protocol
Trigger
Phrases: ".NET MAUI", "MAUI app", "Xamarin", "MAUI Shell", "MAUI page", "MAUI MVVM", "MAUI data binding", "MAUI collection view"
Input Context
- Target platforms (Android, iOS, Windows, macOS)
- Pages and navigation structure
- Data models and service interfaces
- Required platform-specific features
Output Artifact
MAUI solution with: AppShell, Pages with ViewModels, Services, Platform-specific code in Platforms/ folder, CommunityToolkit.Mvvm integration.
Response Format
No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.
Completion Criteria
- AppShell navigation works on all targets
- MVVM bindings resolve without code-behind
- CollectionView renders with DataTemplate
- Platform-specific code compiles under correct target
- App deploys and runs on iOS simulator and Android emulator
Max Response Length
8000 tokens
Architecture Decision Trees
Shell vs NavigationPage
App navigation structure?
├── Tab bar + flyout menu → Shell (FlyoutItem, TabBar, Tab)
│ Pros: Built-in navigation bar, flyout, tabs, search, back behavior
├── Simple stack navigation → NavigationPage
│ Push/pop modal stack, simpler API
└── Tabbed app without flyout → TabbedPage
Simpler than Shell, but less flexible
MVVM Framework
Team preference?
├── CommunityToolkit.Mvvm → Source generators, [ObservableProperty], [RelayCommand]
│ Pros: Minimal boilerplate, compile-time binding validation
├── Prism.Maui → Full MVVM framework, navigation service, DI integration
│ Pros: Navigation service, regions, platform service abstraction
└── Manual INotifyPropertyChanged → Lightweight, no dependency
Cons: More code, no source generators
Platform-Specific Code Strategy
Volume of platform code?
├── Small (1-5 specialized views) → #if ANDROID / #if IOS preprocessor
├── Medium → Platform handlers in MauiProgram.cs ConfigureMauiHandlers
│ Preferred approach — maps cross-platform properties to native views
└── Large → Conditional compilation with partial class files per platform
Use Platforms/Android/, Platforms/iOS/ folders for large blocks
Workflow
- MAUI project architecture — .NET MAUI uses a single-project structure targeting Android, iOS, Windows, and macOS from one codebase. Solution layout:
App.xaml(global styles, resource dictionaries, theme definitions),AppShell.xaml(navigation container with flyout/tabs),Pages/(XAML views with code-behind minimal),ViewModels/(business logic with CommunityToolkit.Mvvm),Models/(data entities, DTOs),Services/(interfaces + implementations registered in DI),Resources/(colors, fonts, images, styles),Platforms/(Android with MainActivity/MainApplication/AndroidManifest, iOS with AppDelegate/Info.plist, Windows, Mac).MauiProgram.csconfigures the app builder, registers services, and sets up handlers.
- Shell navigation — Shell provides flyout (hamburger menu) and TabBar (bottom tabs) navigation containers. Define structure in
AppShell.xaml:FlyoutItemfor menu items,TabBarfor bottom navigation,ShellContentfor pages. Register detail routes withRouting.RegisterRoute("route/name", typeof(Page))in AppShell constructor. Navigate viaShell.Current.GoToAsync("route/name?param=value"). Receive parameters with[QueryProperty(nameof(Param), "param")]attribute orIQueryAttributableinterface. Handle navigation events viaShell.Current.Navigatedevent. Shell provides built-in back button behavior, search handlers, and flyout customization (header template, icon, content templates).
- MVVM with CommunityToolkit.Mvvm — ViewModel base class
ObservableObjectfrom CommunityToolkit.Mvvm. Source generators[ObservableProperty](auto-generates INotifyPropertyChanged),[RelayCommand](auto-generates IRelayCommand from method),[NotifyPropertyChangedFor](notify dependent property on change). Data binding in XAML via{Binding Property}expressions.x:DataTypefor compile-time binding validation. Converters for value transformations (IValueConverter). ViewModel registered as transient in DI — new instance per navigation. Constructor injection for services. Messenger pattern (WeakReferenceMessenger) for cross-ViewModel communication.
- XAML and data binding — XAML markup extensions:
{Binding},{StaticResource},{DynamicResource},{TemplateBinding},{RelativeSource}. Compiled bindings enabled withx:DataTypeon page/control level — compile-time errors for invalid paths.x:Arrayandx:Staticfor static resources. Data templates for item rendering. Control templates for custom control structure. Styles in ResourceDictionary withBasedOn,TargetType,Setter. Triggers:DataTrigger,MultiTrigger,EventTriggerfor state-based styling. VisualStateManager for view states (Normal, Disabled, Focused, Selected).
- MAUI controls —
CollectionView(replaces ListView): vertical/horizontal grids, grouping viaIsGrouped,EmptyViewfor no-data state, pull-to-refresh withRefreshViewwrapper.CarouselViewfor swipeable cards withPeekAreaInsetsandLoopproperties.Borderreplaces Frame for rounded corners.FlexLayoutfor wrapping layouts.GraphicsViewfor custom 2D drawing.BlazorWebViewfor hybrid Blazor + MAUI apps. Handlers architecture replaces the old Custom Renderers system — each control has a mapper that maps cross-platform properties to native views.
- Platform-specific code — Three approaches: (a)
Platforms/folder with conditional compilation — code files inPlatforms/Android/,Platforms/iOS/, etc. are compiled only for the target platform. (b)#if ANDROID,#if IOS,#if WINDOWS,#if MACCATALYSTpreprocessor directives for inline platform branching. (c) Platform handlers inMauiProgram.csviaConfigureMauiHandlers()— customize native controls (e.g., remove Entry underline on Android, set border style on iOS). Map native events to MAUI events. Handler customization is the preferred approach over conditional compilation.
- Deployment and hot reload —
dotnet build -t:Run -f net10.0-androidbuilds and deploys to Android emulator. XAML Hot Reload applies XAML changes instantly during debugging on emulator/simulator (not real-time on physical device). Code signing: Android via.csprojproperties (AndroidSigningKeyStore,AndroidSigningKeyAlias), iOS via provisioning profile in Info.plist. CI/CD: Azure DevOps or GitHub Actions withdotnet publishand platform-specific build steps. App Center was retired in 2025 — use GitHub Actions or Azure Pipelines. UI automation: Appium (Xamarin.UITest is end-of-life).
Platform Compatibility
| Feature | Android | iOS | Windows | macOS (Mac Catalyst) |
|---------|---------|-----|---------|-------|
| Shell navigation (flyout + tabs) | Yes | Yes | Yes | Yes |
| XAML Hot Reload | Yes | Yes | Yes | Yes |
| CollectionView | Yes | Yes | Yes | Yes |
| Handler customization (AppendToMapping) | Yes | Yes | Yes | Yes |
| Target framework moniker | net10.0-android | net10.0-ios | net10.0-windows10.0.19041.0 | net10.0-maccatalyst |
.NET MAUI versions are supported for 18 months; target the current release (.NET 10, LTS) for new work.
Best Practices
- Use compiled bindings (
x:DataType) on every page — catches binding errors at compile time - Register all services and ViewModels in
MauiProgram.cs— no service locator pattern - Keep code-behind to DI constructor + InitializeComponent calls only
- Prefer
BorderoverFrame— Frame is deprecated for rendering performance - Use
CommunityToolkit.Mauifor behaviors, converters, animations, and popups - Version
Platforms/code with#ifblocks — never duplicate entire files per platform
Common Pitfalls
- Missing linker configuration: .NET MAUI linker strips unused assemblies. Add
Preserveattribute or linker config XML for dynamically accessed types. - CollectionView inside ScrollView: gives the list infinite height, so virtualization stops and every item is created. Use
CollectionViewalone withHeader/Footer, or a fixed-height container. - iOS simulator keyboard: Hardware keyboard on simulator doesn't trigger
Completedevent. Test keyboard on real device. - Android cleartext traffic: blocked by default. Fix the server to use HTTPS; for local development only, allow a specific host through
network_security_config.xmlinstead of settingusesCleartextTraffic="true"app-wide. - XAML Hot Reload limitations: Doesn't work for constructor changes, new page creation, or C# changes — only XAML property edits.
Anti-Patterns
- Code-behind with business logic: Keep to DI constructor + InitializeComponent
- Singleton ViewModels: ViewModels should be transient — new instance per navigation
- Messaging abuse: WeakReferenceMessenger for cross-ViewModel, not for general pub-sub
- Direct static navigation calls: Use Shell routing — never instantiate pages directly
- Platform API calls without #if guard: Platform-specific APIs crash on unsupported targets
- Ignoring linker configuration: Linker strips dynamically accessed types — preserve them explicitly
Performance Optimization
Startup Performance
MAUI app startup involves: native initialization, XAML parsing, Shell construction, and first-page rendering. Profile with: dotnet-trace (event tracing), Xamarin Profiler (legacy), or custom stopwatch logging. Key optimizations:
- AOT compilation: iOS/Mac Catalyst are always AOT-compiled (no JIT on iOS). Native AOT (
<PublishAot>true</PublishAot>) is available for iOS and Mac Catalyst (experimental in .NET 8, supported from .NET 9) and gives smaller, faster-starting apps but requires trim-safe code (compiled bindings, no unbounded reflection). On Android, use startup-tracing/profiled AOT (<AndroidEnableProfiledAot>, default in Release) rather than full AOT unless you measured a win. - Trim assemblies:
<TrimMode>full</TrimMode>with linker configuration. Reduces app size but requires[DynamicallyAccessedMembers]attributes on types accessed via reflection. - Lazy initialization: Defer non-critical services:
Lazy<IService>orTask.Run(() => InitializeHeavyService())after first frame render. Register heavy services as transient or useLazy<T>wrapper. - Page lifetime: Shell keeps pages on its navigation stacks alive; register pages/ViewModels as transient and release subscriptions when a page is popped. (
CachingStrategy.RecycleElementis aListViewsetting, not a Shell one;CollectionViewvirtualizes by default.) - Startup tracing: Measure with
ActivityorDiagnosticListenerbetweenApplication.OnStart()and first frameAppearingevent. Target: <2s cold start on mid-range Android/iOS devices.
Memory Management
- CollectionView recycling: Virtualization recycles cell templates — ensure views are data-bound, not created in
ItemTemplatecode-behind. AvoidDataTemplatewith complex nested layouts. - Image caching:
UriImageSourcecaches downloaded images on disk (CachingEnabled,CacheValidity, default one day). Downsample large images before display and avoidImageSource.FromStreamwork on the UI thread. FFImageLoading is unmaintained; evaluate maintained community forks before adopting one. - Weak event patterns: Event subscriptions (PropertyChanged, CollectionChanged) prevent GC of pages. Use
WeakEventManagerorWeakReferencefor subscribers. - Dispose pattern: Implement
IDisposableon ViewModels that hold subscriptions. CallDispose()in pageOnDisappearingor viaLifecycleevents. Unsubscribe fromWeakReferenceMessenger(MessagingCenteris obsolete; migrate it) in ViewModel cleanup. - Large collection handling: For 1000+ items, use
CollectionViewwithRemainingItemsThreshold+RemainingItemsThresholdReachedCommandfor incremental loading (infinite scroll). Never load all items into memory at once.
UI Thread and Responsiveness
- Async all the way: All I/O-bound operations (HTTP, database, file system) must use
async/await. Never call.Resultor.Wait()on Task — this deadlocks on MAUI's main thread. MainThread.BeginInvokeOnMainThread: Only use for UI updates from background threads. Batch UI updates — don't invoke per-item in a loop.- Layout passes: Minimize layout pass count. Use
HorizontalStackLayout/VerticalStackLayoutoverStackLayout(lighter). AvoidAbsoluteLayoutfor dynamic layouts (measuring pass is expensive). PreferGridwith proportional rows/columns. - XAML compilation: XamlC is on by default for .NET MAUI projects (no
[XamlCompilation]attribute needed); .NET 10 adds the XAML source generator (<MauiXamlInflator>SourceGen</MauiXamlInflator>), which also removes runtime XAML parsing. Keep compiled bindings everywhere.
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
- Data binding performance: Prefer compiled bindings (
x:DataType) over reflection-based bindings. Compiled bindings reduce reflection overhead and catch errors at compile time. For list items, ensurex:DataTypeonDataTemplateis set to the item type.
<CollectionView ItemsSource="{Binding Orders}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="models:Order">
<Label Text="{Binding CustomerName}" />
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Graphics and Animation
- GPU-accelerated properties: Animate
Opacity,Rotation,Scale,TranslationX/TranslationY(GPU-composited). Avoid animatingWidth,Height,Margin,Padding(trigger layout passes). GraphicsViewover custom drawing: MAUI'sGraphicsViewusesMicrosoft.Maui.Graphicsfor 2D drawing — hardware-accelerated on most platforms. Use for custom charts, signatures, diagrams.- Reduce shadow/blur: Shadows (
Shadoweffect) and blurs trigger off-screen rendering. Use sparingly in lists. Prefer flat design for list items, reserve shadows for modals/popups.
Build & Deployment Patterns
Project Configuration (.csproj)
<PropertyGroup>
<TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>
<OutputType>Exe</OutputType>
<UseMaui>true</UseMaui>
<SingleProject>true</SingleProject>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- Release optimizations -->
<PublishTrimmed>true</PublishTrimmed>
<PublishAot>false</PublishAot>
<TrimMode>partial</TrimMode>
<Optimize>true</Optimize>
</PropertyGroup>
<!-- Android-specific -->
<PropertyGroup Condition="$(TargetFramework.Contains('android'))">
<ApplicationId>com.company.app</ApplicationId>
<ApplicationVersion>1</ApplicationVersion>
<ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
<AndroidSigningKeyStore>$(ProjectDir)release.keystore</AndroidSigningKeyStore>
<AndroidSigningKeyAlias>app-alias</AndroidSigningKeyAlias>
<AndroidSigningKeyPass>$(KS_PASS)</AndroidSigningKeyPass>
<AndroidSigningStorePass>$(KSP_PASS)</AndroidSigningStorePass>
<AndroidPackageFormat>aab</AndroidPackageFormat>
</PropertyGroup>
<!-- iOS-specific -->
<PropertyGroup Condition="$(TargetFramework.Contains('ios'))">
<ApplicationId>com.company.app</ApplicationId>
<BuildIpa>true</BuildIpa>
<RuntimeIdentifier>ios-arm64</RuntimeIdentifier>
<CodesignKey>Apple Distribution: Company Name</CodesignKey>
<CodesignProvision>$(APPLE_PROVISIONING_PROFILE)</CodesignProvision>
<ArchiveOnBuild>true</ArchiveOnBuild>
</PropertyGroup>
CI/CD Pipeline (GitHub Actions)
name: Build and Deploy MAUI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build-android:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Restore
run: dotnet restore
- name: Build Android
run: |
dotnet publish -f net10.0-android -c Release `
-p:AndroidKeyStore=true `
-p:AndroidSigningKeyStore=release.keystore `
-p:AndroidSigningKeyAlias=app-alias `
-p:AndroidSigningKeyPass=${{ secrets.KEY_PASS }} `
-p:AndroidSigningStorePass=${{ secrets.STORE_PASS }}
- name: Verify AAB signature
run: jarsigner -verify bin/Release/net10.0-android/publish/*-Signed.aab
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: android-release
path: '**/*.aab'
build-ios:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '10.0.x'
- name: Install iOS provisioning
run: |
echo ${{ secrets.IOS_CERT }} | base64 --decode > cert.p12
echo ${{ secrets.IOS_PROVISIONING }} | base64 --decode > provisioning.mobileprovision
security create-keychain -p temp temp.keychain
security import cert.p12 -k temp.keychain -P ${{ secrets.CERT_PASS }}
- name: Build iOS
run: |
dotnet build -f net10.0-ios --configuration Release `
-p:RuntimeIdentifier=ios-arm64 `
-p:CodesignKey="Apple Distribution: Company" `
-p:CodesignProvision="$(ls provisioning.mobileprovision)"
- name: Upload IPA
uses: actions/upload-artifact@v4
with:
name: ios-release
path: '**/*.ipa'
App Store & Play Store Submission
Google Play: Build AAB with dotnet publish -f net10.0-android -c Release. Sign with Android keystore (jarsigner or MSBuild properties). Upload to Google Play Console → Internal Testing → Closed Alpha → Open Beta → Production. Test an AAB locally with bundletool: java -jar bundletool.jar build-apks --bundle=app.aab --output=app.apks --connected-device then java -jar bundletool.jar install-apks --apks=app.apks.
Apple App Store: Build IPA with dotnet publish -f net10.0-ios -c Release. Requires Apple Developer Program membership ($99/year). Distribution via App Store Connect: Xcode Organizer → Distribute App → App Store Connect. Or use Transporter app for IPA upload. TestFlight for beta distribution before production release.
App Center was retired on 2025-03-31 (Distribute included). Use GitHub Actions or Azure Pipelines for builds, Firebase App Distribution for Android beta testing, TestFlight for iOS.
Versioning Strategy
ApplicationVersion(Android): integer, auto-increment per release.CFBundleVersion(iOS): same integer, matches Android version code.ApplicationDisplayVersion/CFBundleShortVersionString: semver string ("1.2.3").- Sync via CI: read from
version.txtor Git tag, inject into .csproj properties via script orDirectory.Build.props.
Platform-Specific Code Examples
Android — Custom Handler (Remove Entry Underline)
// MauiProgram.cs
builder.ConfigureMauiHandlers(handlers => {
handlers.AddHandler<Entry, EntryHandler>(nameof(Entry), (handler) => {
#if ANDROID
handler.PlatformView.BackgroundTintList = Android.Content.Res.ColorStateList.ValueOf(
Android.Graphics.Color.Transparent);
#endif
});
});
iOS — Safe Area Handling
// iOS — respect safe area in custom views
#if IOS
using UIKit;
using CoreGraphics;
public class SafeAreaAwareView : UIView
{
public override void LayoutSubviews()
{
base.LayoutSubviews();
var insets = Window?.SafeAreaInsets ?? UIEdgeInsets.Zero;
// Adjust layout based on safe area
}
}
#endif
Windows — Title Bar Customization
#if WINDOWS
using Microsoft.UI.Xaml;
using Microsoft.UI;
public static class WindowTitleBar
{
public static void SetTheme(Window window, bool darkMode)
{
var nativeWindow = window.Handler?.PlatformView as Microsoft.UI.Xaml.Window;
if (nativeWindow != null)
{
nativeWindow.ExtendsContentIntoTitleBar = true;
// Custom title bar colors
}
}
}
#endif
Shared Service with Platform DI
// Interface in shared code
public interface IDeviceInfo
{
string GetDeviceName();
string GetOSVersion();
}
// Android implementation (Platforms/Android/)
public class AndroidDeviceInfo : IDeviceInfo
{
public string GetDeviceName() =>
Android.OS.Build.Model ?? "Unknown";
public string GetOSVersion() =>
Android.OS.Build.VERSION.Release ?? "Unknown";
}
// iOS implementation (Platforms/iOS/)
public class IosDeviceInfo : IDeviceInfo
{
public string GetDeviceName() =>
UIKit.UIDevice.CurrentDevice.Name;
public string GetOSVersion() =>
UIKit.UIDevice.CurrentDevice.SystemVersion;
}
// Registration in MauiProgram.cs
#if ANDROID
builder.Services.AddSingleton<IDeviceInfo, AndroidDeviceInfo>();
#elif IOS
builder.Services.AddSingleton<IDeviceInfo, IosDeviceInfo>();
#endif
Anti-Patterns (Expanded)
- Static service locator:
Application.Current.MainPageorDependencyService.Get<T>()creates hidden dependencies. Use constructor DI only. - Massive MauiProgram.cs: Registering every service and handler inline in MauiProgram.cs creates an unmaintainable file. Use extension methods:
builder.Services.AddOrderModule(),builder.ConfigurePaymentHandlers(). - Direct ObservableCollection manipulation: Adding/removing items on background thread crashes. Use
MainThread.BeginInvokeOnMainThread(() => collection.Add(item)). - Overusing Effects: Effects are procedural and harder to override. Use Handlers for MAUI-native customization, Effects only for pre-MAUI migration code.
- Ignoring linker configuration: Linker strips unused IL. Types accessed via reflection (Sqlite, serialization) must be preserved. Use
[Preserve]attribute or linker XML configuration. - Missing
#ifon platform APIs:Android.Graphics.Colorin shared code compiles on all targets but throws on iOS. Always guard platform-specific types with#if ANDROID,#if IOS. - Nested layouts in ListView: ListView/CollectionView with complex nested layouts (Grid in StackLayout in Frame) kills scroll performance. Flatten hierarchy for list items.
- No
x:DataTypeon DataTemplate: Reflection-based bindings in lists are measurably slower than compiled bindings and are not trimming/AOT safe. Always setx:DataTypeon ItemTemplate DataTemplate. - Storing secrets in code: API keys, connection strings in source code. Use Azure Key Vault, GitHub Secrets, or
Secrets.json(user secrets in development). Never commit secrets. - Over-engineering with Prism: Prism adds significant complexity for most apps. CommunityToolkit.Mvvm covers most MVVM needs with less overhead.
Configuration Reference
<!-- .csproj — Android signing -->
<PropertyGroup Condition="$(TargetFramework.Contains('android'))">
<AndroidSigningKeyStore>release.keystore</AndroidSigningKeyStore>
<AndroidSigningKeyAlias>app-alias</AndroidSigningKeyAlias>
</PropertyGroup>
<!-- .csproj — iOS version -->
<PropertyGroup Condition="$(TargetFramework.Contains('ios'))">
<CFBundleVersion>1.0.0</CFBundleVersion>
<CFBundleShortVersionString>1.0</CFBundleShortVersionString>
</PropertyGroup>
References
- references/dotnet-maui-advanced.md — Dotnet Maui Advanced Topics
- references/dotnet-maui-fundamentals.md — Dotnet Maui Fundamentals
- references/maui-architecture.md — MAUI Architecture
- references/maui-controls.md — MAUI Controls
- references/maui-mvvm.md — MAUI MVVM with CommunityToolkit
- references/maui-structure.md — MAUI Project Structure
Handoff
Hand off to iOS/Android native skills when platform handler customization requires deep UIKit or Android Views API knowledge.