Dotnet maui

From j4flmao/agent-skills · View interactive version

Dotnet maui is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about .NET MAUI apps, MAUI Shell navigation, MVVM with CommunityToolkit, data binding, CollectionView, handlers or migrating from Xamarin.Forms. Produces cross-platform C#/XAML app structure, platform code and release setup. Not for C# language features (use lang-csharp) or AS

How to use this skill

Skill file

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

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

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

  1. 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.cs configures the app builder, registers services, and sets up handlers.
  1. Shell navigation — Shell provides flyout (hamburger menu) and TabBar (bottom tabs) navigation containers. Define structure in AppShell.xaml: FlyoutItem for menu items, TabBar for bottom navigation, ShellContent for pages. Register detail routes with Routing.RegisterRoute("route/name", typeof(Page)) in AppShell constructor. Navigate via Shell.Current.GoToAsync("route/name?param=value"). Receive parameters with [QueryProperty(nameof(Param), "param")] attribute or IQueryAttributable interface. Handle navigation events via Shell.Current.Navigated event. Shell provides built-in back button behavior, search handlers, and flyout customization (header template, icon, content templates).
  1. MVVM with CommunityToolkit.Mvvm — ViewModel base class ObservableObject from 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:DataType for 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.
  1. XAML and data binding — XAML markup extensions: {Binding}, {StaticResource}, {DynamicResource}, {TemplateBinding}, {RelativeSource}. Compiled bindings enabled with x:DataType on page/control level — compile-time errors for invalid paths. x:Array and x:Static for static resources. Data templates for item rendering. Control templates for custom control structure. Styles in ResourceDictionary with BasedOn, TargetType, Setter. Triggers: DataTrigger, MultiTrigger, EventTrigger for state-based styling. VisualStateManager for view states (Normal, Disabled, Focused, Selected).
  1. MAUI controls — CollectionView (replaces ListView): vertical/horizontal grids, grouping via IsGrouped, EmptyView for no-data state, pull-to-refresh with RefreshView wrapper. CarouselView for swipeable cards with PeekAreaInsets and Loop properties. Border replaces Frame for rounded corners. FlexLayout for wrapping layouts. GraphicsView for custom 2D drawing. BlazorWebView for 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.
  1. Platform-specific code — Three approaches: (a) Platforms/ folder with conditional compilation — code files in Platforms/Android/, Platforms/iOS/, etc. are compiled only for the target platform. (b) #if ANDROID, #if IOS, #if WINDOWS, #if MACCATALYST preprocessor directives for inline platform branching. (c) Platform handlers in MauiProgram.cs via ConfigureMauiHandlers() — 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.
  1. Deployment and hot reload — dotnet build -t:Run -f net10.0-android builds 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 .csproj properties (AndroidSigningKeyStore, AndroidSigningKeyAlias), iOS via provisioning profile in Info.plist. CI/CD: Azure DevOps or GitHub Actions with dotnet publish and 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

Common Pitfalls

Anti-Patterns

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:

Memory Management

UI Thread and Responsiveness

[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
<CollectionView ItemsSource="{Binding Orders}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:Order">
            <Label Text="{Binding CustomerName}" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Graphics and Animation

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

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)

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

Handoff

Hand off to iOS/Android native skills when platform handler customization requires deep UIKit or Android Views API knowledge.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.