loading experience

Guide

Guide to .NET MAUI: cross-platform apps, from navigation to publishing

Guide to .NET MAUI: cross-platform apps, from navigation to publishing

This guide gathers in a single path the articles on .NET MAUI: what is new in .NET 10, the MVVM model with CommunityToolkit.Mvvm, navigation with Shell, lists with CollectionView, MAUI Blazor Hybrid, permissions and device APIs, startup performance and publishing to Google Play and the App Store. Read it from start to finish or jump to the section you need.

In this guide

  1. .NET MAUI in .NET 10: quality, compiled XAML and deprecated controls
  2. MVVM in .NET MAUI with CommunityToolkit.Mvvm
  3. Navigation in .NET MAUI with Shell and parameters
  4. CollectionView in .NET MAUI: fast, flexible lists
  5. MAUI Blazor Hybrid: the same interface on the web and in apps
  6. .NET MAUI: permissions and device APIs
  7. .NET MAUI: apps that start quickly and scroll smoothly
  8. Publishing a .NET MAUI app to Google Play and the App Store

.NET MAUI in .NET 10: quality, compiled XAML and deprecated controls

.NET MAUI lets you write a single C# and XAML application for Android, iOS, macOS and Windows, using each platform's native controls. In .NET 10 the work focused on quality, performance and API clean-up.

Deprecation warnings are the list of things to update.
Deprecation warnings are the list of things to update.

XAML generated at compile time

The XAML source generator turns pages into C# code during compilation, instead of interpreting them at startup. Markup errors show up earlier and pages open faster.

<PropertyGroup>
  <MauiXamlInflator>SourceGen</MauiXamlInflator>
</PropertyGroup>

Deprecated controls and APIs

  • ListView and TableView are deprecated: CollectionView is the control to use for lists.
  • MessagingCenter is no longer public: use the CommunityToolkit's WeakReferenceMessenger.
  • Application.MainPage gives way to overriding CreateWindow.
public partial class App : Application
{
    public App() => InitializeComponent();

    protected override Window CreateWindow(IActivationState? activationState) =>
        new(new AppShell());
}

Other improvements

  • Finer control of safe areas (notches, system bars) for each edge of the screen.
  • Multiple selection of photos and videos in the media picker.
  • Improved interoperability between C# and JavaScript in HybridWebView.
  • Support for the latest Android and iOS versions.

How to upgrade

Change the target frameworks to net10.0-android, net10.0-ios and so on, update the workloads with dotnet workload update and tackle the deprecation warnings first: they are the list of things to fix before they become errors.


MVVM in .NET MAUI with CommunityToolkit.Mvvm

The MVVM pattern separates the interface (View) from presentation logic (ViewModel). The CommunityToolkit.Mvvm package removes almost all the boilerplate thanks to source generators.

The View displays, the ViewModel decides, services work on the data.
The View displays, the ViewModel decides, services work on the data.

A complete ViewModel

public partial class ProfileViewModel(IProfileService service) : ObservableObject
{
    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(SaveCommand))]
    public partial string Name { get; set; } = "";

    [ObservableProperty]
    public partial bool IsSaving { get; set; }

    private bool CanSave() => !string.IsNullOrWhiteSpace(Name) && !IsSaving;

    [RelayCommand(CanExecute = nameof(CanSave))]
    private async Task SaveAsync()
    {
        IsSaving = true;
        try { await service.SaveAsync(Name); }
        finally { IsSaving = false; }
    }
}

The generator creates the property change notifications and the SaveCommand command, which enables and disables itself based on CanSave.

The View

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:MyApp.ViewModels"
             x:DataType="vm:ProfileViewModel">
    <VerticalStackLayout Padding="20" Spacing="12">
        <Entry Text="{Binding Name}" Placeholder="Name" />
        <Button Text="Save" Command="{Binding SaveCommand}" />
        <ActivityIndicator IsRunning="{Binding IsSaving}" />
    </VerticalStackLayout>
</ContentPage>

x:DataType enables compiled bindings: checked at compile time and faster at runtime.

Registration

builder.Services.AddSingleton<IProfileService, ProfileService>();
builder.Services.AddTransient<ProfileViewModel>();
builder.Services.AddTransient<ProfilePage>();

The page receives the ViewModel in its constructor and assigns it to the BindingContext. To let different ViewModels communicate without direct references, use WeakReferenceMessenger, which replaces the old MessagingCenter.


Navigation in .NET MAUI with Shell and parameters

Shell provides the navigation structure of a MAUI app: tabs, flyout menu and route-based navigation, similar to web addresses.

Objects travel between pages without being turned into strings.
Objects travel between pages without being turned into strings.

The app structure

<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:views="clr-namespace:MyApp.Views"
       x:Class="MyApp.AppShell">
    <TabBar>
        <ShellContent Title="Orders" Icon="orders.png" ContentTemplate="{DataTemplate views:OrdersPage}" Route="orders" />
        <ShellContent Title="Profile" Icon="profile.png" ContentTemplate="{DataTemplate views:ProfilePage}" Route="profile" />
    </TabBar>
</Shell>

Routes for detail pages

public AppShell()
{
    InitializeComponent();
    Routing.RegisterRoute("orders/detail", typeof(OrderDetailPage));
}

// from a ViewModel
await Shell.Current.GoToAsync("orders/detail", new ShellNavigationQueryParameters
{
    ["Order"] = selectedOrder
});

Receiving the parameters

The destination page's ViewModel implements IQueryAttributable and receives the objects passed in, without having to serialise them into a string:

public partial class OrderDetailViewModel : ObservableObject, IQueryAttributable
{
    [ObservableProperty]
    public partial Order? Order { get; set; }

    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        if (query.TryGetValue("Order", out var o)) Order = o as Order;
    }
}

Going back

GoToAsync("..") returns to the previous page and can also pass parameters, which is useful to return a choice made on a selection page.

A tip: centralise route names in constants. A mistyped route is only discovered when the user taps the button.


CollectionView in .NET MAUI: fast, flexible lists

With ListView deprecated in .NET 10, CollectionView is the control for displaying lists of data. It is more flexible and more efficient, because it recycles cells while scrolling.

Only the data the user is about to see gets loaded.
Only the data the user is about to see gets loaded.

A list with an item template

<CollectionView ItemsSource="{Binding Products}"
                SelectionMode="Single"
                SelectionChangedCommand="{Binding OpenCommand}"
                SelectionChangedCommandParameter="{Binding SelectedItem, Source={RelativeSource Self}}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:Product">
            <Grid Padding="12" ColumnDefinitions="*,Auto">
                <Label Text="{Binding Name}" FontAttributes="Bold" />
                <Label Grid.Column="1" Text="{Binding Price, StringFormat='{0:C}'}" />
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
    <CollectionView.EmptyView>
        <Label Text="No products found" HorizontalOptions="Center" />
    </CollectionView.EmptyView>
</CollectionView>

Grid instead of list

<CollectionView.ItemsLayout>
    <GridItemsLayout Orientation="Vertical" Span="2" HorizontalItemSpacing="8" VerticalItemSpacing="8" />
</CollectionView.ItemsLayout>

Incremental loading

For long lists, load data in pages as the user approaches the end:

<CollectionView ItemsSource="{Binding Products}"
                RemainingItemsThreshold="5"
                RemainingItemsThresholdReachedCommand="{Binding LoadMoreCommand}" />

Performance tips

  • Use ObservableCollection and add items instead of replacing the whole collection.
  • Keep cell templates simple: few nested layout levels.
  • Set x:DataType in DataTemplates for compiled bindings.
  • Resize images on the server: loading huge photos into a list is the quickest way to slow it down.

MAUI Blazor Hybrid: the same interface on the web and in apps

With Blazor Hybrid, Razor components run directly inside the native .NET MAUI app and are displayed through an embedded web control. There is no server and no WebAssembly: the C# code runs on the device, with full access to its APIs.

The same interface code serves the web and the native apps.
The same interface code serves the web and the native apps.

Why choose it

  • Reuse: the same pages and components serve the website and the phone and desktop apps.
  • Web skills: HTML and CSS for the interface, C# for the logic.
  • Native features: camera, files, notifications and sensors remain available.

The recommended structure

The "MAUI Blazor Hybrid and Web App" template creates three projects: a shared Razor library with the components, the MAUI app and the web application. Platform-dependent features are defined as interfaces in the shared library and implemented separately.

// shared library
public interface IFormFactor
{
    string Device { get; }
}

// MAUI app
public class MauiFormFactor : IFormFactor
{
    public string Device => DeviceInfo.Current.Idiom.ToString();
}

// web app
public class WebFormFactor : IFormFactor
{
    public string Device => "Web";
}
@inject IFormFactor FormFactor

<p>You are using: @FormFactor.Device</p>

Things to know

  • The look is the web's, not that of native controls: design for small screens carefully.
  • The system's embedded web control (WebView2 on Windows, WKWebView on iOS and macOS, WebView on Android) affects compatibility and performance.
  • You can mix native XAML pages and Blazor pages in the same app.

For teams that already have a Blazor application, it is the fastest way to reach the app stores without rewriting the interface.


.NET MAUI: permissions and device APIs

.NET MAUI exposes device features through APIs shared by every platform: location, camera, files, connectivity, device information. Before using them, though, you need permissions.

The app must keep working when the user says no.
The app must keep working when the user says no.

Requesting a permission

public async Task<Location?> CurrentLocationAsync()
{
    var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
    if (status != PermissionStatus.Granted)
        status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();

    if (status != PermissionStatus.Granted)
        return null; // the user refused: the app must keep working

    return await Geolocation.Default.GetLocationAsync(
        new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10)));
}

On Android and iOS, permissions must also be declared in the platform files (AndroidManifest.xml and Info.plist), with a clear explanation of why: the stores check it.

Picking a photo

var photo = await MediaPicker.Default.PickPhotoAsync();
if (photo is not null)
{
    await using var stream = await photo.OpenReadAsync();
    await _upload.SendAsync(stream, photo.FileName);
}

Connectivity

if (Connectivity.Current.NetworkAccess != NetworkAccess.Internet)
{
    await Shell.Current.DisplayAlert("Offline", "Data will be sent as soon as you are back online.", "OK");
}

Good practices

  • Ask for permissions only when needed, in a context where the user understands why.
  • Always handle refusal: the app must not get stuck.
  • For features not covered by the shared APIs, use platform-specific code in the Platforms folders or partial classes.

.NET MAUI: apps that start quickly and scroll smoothly

An app that is slow to start gets uninstalled. These are the techniques with the biggest impact on the performance of a .NET MAUI app.

Simple changes, big effects on budget devices.
Simple changes, big effects on budget devices.

1. Simple layouts

Every nested layout level costs measuring and drawing time. A Grid with rows and columns often replaces three or four nested StackLayouts.

2. Compiled bindings

With x:DataType on pages and DataTemplates, bindings are resolved at compile time instead of through reflection at runtime.

3. Keep work away from startup

public partial class HomeViewModel(ICatalog catalog) : ObservableObject
{
    [ObservableProperty]
    public partial IReadOnlyList<Product> Featured { get; set; } = [];

    // called by the page in OnAppearing, not in the constructor
    [RelayCommand]
    private async Task LoadAsync() => Featured = await catalog.FeaturedAsync();
}

Register services as transient or lazy, load data when the page appears and postpone everything the first screen does not need.

4. Trimming and AOT

In Release, trimming removes unused code and reduces the app size. On iOS and Mac Catalyst you can enable Native AOT, for faster startup and lower memory use:

<PropertyGroup Condition="'$(TargetFramework)' == 'net10.0-ios'">
  <PublishAot>true</PublishAot>
</PropertyGroup>

5. Images

Use images sized for the screen, compressed formats and caching for those downloaded from the network. A ten-megapixel image in a thumbnail wastes memory and time.

Measure

Always test in Release configuration on real devices, including budget ones: the emulator on a powerful PC hides many problems.


Publishing a .NET MAUI app to Google Play and the App Store

Reaching the stores is the last mile of every mobile app. With .NET MAUI you start from the same project, but each platform has its own rules.

One project, two signing and publishing paths.
One project, two signing and publishing paths.

Android: signed AAB package

Google Play requires the AAB (Android App Bundle) format signed with an upload key. The key is created once and must be kept safe: without it you cannot publish updates.

dotnet publish -f net10.0-android -c Release \
  -p:AndroidKeyStore=true \
  -p:AndroidSigningKeyStore=upload-key.keystore \
  -p:AndroidSigningKeyAlias=upload \
  -p:AndroidSigningKeyPass=env:ANDROID_KEY_PASS \
  -p:AndroidSigningStorePass=env:ANDROID_STORE_PASS

Passwords are read from environment variables: never write them in the project file.

iOS: certificates and provisioning

For iOS you need a Mac (remote is fine), an Apple Developer account, a distribution certificate and a provisioning profile for the app. Publishing produces an IPA package to upload with Apple's tools.

dotnet publish -f net10.0-ios -c Release -p:ArchiveOnBuild=true \
  -p:CodesignKey="Apple Distribution: Company Ltd" \
  -p:CodesignProvision="MyApp App Store Profile"

Checks before submitting

  • Version: ApplicationDisplayVersion for the user and ApplicationVersion, a number that must always increase.
  • Icons and splash screen defined once in the MAUI project and generated for each platform.
  • Privacy policy and data collection declarations, required by both stores.
  • Permission texts that are clear and consistent with actual use.
  • Tests on real devices, in Release, before every submission.

Automate

A continuous integration pipeline that builds, signs and uploads the test version reduces errors and time: releasing becomes a repeatable operation, not a manual ritual.


Comments (0)

No comments yet.

Leave a comment