Navigation and state
Navigation and state
Navigation changes the page or route a user sees; state describes what the app knows and what the user has entered. Plan their lifetimes independently: a page can disappear while a draft should survive, and a process can be terminated before a lifecycle callback finishes.
Shell supports a URI-style route hierarchy. Register detail routes once, await GoToAsync, and use relative navigation to return from a pushed detail route. Guard rapid repeated taps and handle navigation errors. Pass stable identifiers rather than whole sensitive records in route strings. Keep draft state separate from saved state and make discard or save explicit. When saving asynchronously, record the snapshot that actually persisted rather than blindly marking a newer edited draft clean. Do not use QueryPropertyAttribute with full trimming or Native AOT: the MAUI navigation guide recommends IQueryAttributable instead. Validate received route data and distinguish query decoding behavior from path parameter decoding. OnAppearing may be called repeatedly, so do not overwrite a dirty edit each time. Window lifecycle events such as Stopped and Resumed provide opportunities for cleanup or refresh, but are not a guarantee of persistence before termination. Preferences is a small non-secret key/value store, not a transactional note database or secret vault; use app data storage or a reviewed database for larger data and secure storage for actual secrets. The examples store only synthetic local values and provide a reset action.
Baseline: .NET 10 / C# 14. Every expected result is reasoned, not executed. The complete portable and Windows desktop projects are separate from MAUI template overlays. No runtime or UI claims.
Navigate to a registered detail page
Open details, read the synthetic note, then press Back. Repeat once.
In an approved environment with .NET 10 SDK and MAUI 10 workload already available, create a fresh disposable standard MAUI app with dotnet new maui -n Fixture -o Fixture --no-restore. Confirm namespace Fixture, standard Shell root, target framework, resource paths, and actual template compatibility; stop on mismatch. Copy the archived Program.cs AS MainPage.xaml.cs (replace, do not add a duplicate). Replace MainPage.xaml and any named companion in the generated project. Keep the template project, platform startup and assets. Inspect dependency graph and target tooling before approved restore/build; use the actual target framework from the template. Run only on an authorized emulator or disposable device. No silent installation, signing, or publishing.
using System;using Microsoft.Maui.Controls;using Microsoft.Maui;namespace Fixture;public partial class MainPage : ContentPage { private bool busy; public MainPage() { InitializeComponent(); } private async void Open(object? sender, EventArgs e) { if(busy) return; busy=true; OpenButton.IsEnabled=false; try { await Shell.Current.GoToAsync("fixture-note-detail"); } catch(Exception) { Status.Text="Navigation failed"; } finally { busy=false; OpenButton.IsEnabled=true; } }}public sealed class DetailPage : ContentPage { public DetailPage() { Title="Details"; Content=new VerticalStackLayout { Padding=20, Children={new Label { Text="Atlas — sample note" }} }; }}MainPage.xaml
<ContentPage x:Class="Fixture.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" Title="Notes lab"> <VerticalStackLayout Padding="20" Spacing="12"> <Label Text="Notes"/> <Button x:Name="OpenButton" Text="Open details" Clicked="Open"/> <Label x:Name="Status"/> </VerticalStackLayout></ContentPage>AppShell.xaml.cs
using Microsoft.Maui.Controls;namespace Fixture;public partial class AppShell : Shell { public AppShell() { InitializeComponent(); Routing.RegisterRoute("fixture-note-detail", typeof(DetailPage)); }}Expected result (not executed):
Open: Details page shows Atlas — sample note. Back: Notes page.The template Shell hosts MainPage. The route is registered in the companion AppShell constructor, and the tap guard avoids concurrent pushes.
Save and reset a synthetic preference
Enter Atlas, save, restart the isolated fixture, then reset. Do not enter real notes.
In an approved environment with .NET 10 SDK and MAUI 10 workload already available, create a fresh disposable standard MAUI app with dotnet new maui -n Fixture -o Fixture --no-restore. Confirm namespace Fixture, standard Shell root, target framework, resource paths, and actual template compatibility; stop on mismatch. Copy the archived Program.cs AS MainPage.xaml.cs (replace, do not add a duplicate). Replace MainPage.xaml and any named companion in the generated project. Keep the template project, platform startup and assets. Inspect dependency graph and target tooling before approved restore/build; use the actual target framework from the template. Run only on an authorized emulator or disposable device. No silent installation, signing, or publishing.
using System;using Microsoft.Maui.Controls;using Microsoft.Maui;namespace Fixture;public partial class MainPage : ContentPage { private const string Key="bytemind_v24_demo_note"; public MainPage() { InitializeComponent(); Input.Text=Microsoft.Maui.Storage.Preferences.Default.Get(Key,""); } private void Save(object? sender, EventArgs e) { string note=Input.Text?.Trim() ?? ""; if(note.Length is <1 or >40) { Status.Text="Enter 1 to 40 characters"; return; } Microsoft.Maui.Storage.Preferences.Default.Set(Key,note); Status.Text="Saved sample"; } private void Reset(object? sender, EventArgs e) { Microsoft.Maui.Storage.Preferences.Default.Remove(Key); Input.Text=""; Status.Text="Sample removed"; }}MainPage.xaml
<ContentPage x:Class="Fixture.MainPage" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" Title="Notes lab"> <ScrollView> <VerticalStackLayout Padding="20" Spacing="12"> <Label Text="Synthetic preference"/> <Entry x:Name="Input" SemanticProperties.Description="Sample note"/> <Button Text="Save sample" Clicked="Save"/> <Button Text="Reset sample" Clicked="Reset"/> <Label x:Name="Status"/> </VerticalStackLayout> </ScrollView></ContentPage>Expected result (not executed):
Save Atlas: Saved sample. Restart: Atlas. Reset then restart: blank.The key belongs to this isolated fixture. Remove only that key; do not clear unrelated app data. Actual persistence across lifecycle transitions needs device verification.
Model a draft and explicit discard
Trace editing without mutating saved state until Save is called.
Use the complete Fixture.csproj with an approved .NET 10 SDK. Restore approved dependencies, build and run. No UI workload needed.
using System;var state=new NoteEditor("Atlas");state.Draft="Comet";Console.WriteLine($"dirty={state.IsDirty}; saved={state.Saved}");state.Discard();Console.WriteLine($"dirty={state.IsDirty}; draft={state.Draft}");state.Draft="Nova"; state.Save();Console.WriteLine($"saved={state.Saved}");sealed class NoteEditor(string saved) { public string Saved {get;private set;}=saved; public string Draft {get;set;}=saved; public bool IsDirty=>Draft!=Saved; public void Discard()=>Draft=Saved; public void Save()=>Saved=Draft;}Expected result (not executed):
dirty=True; saved=Atlasdirty=False; draft=Atlassaved=NovaIn-memory state is not durable storage. A UI should handle dirty navigation and only mark a draft saved after persistence succeeds.
Apply the concept
Plan a list-to-edit route with dirty changes and app backgrounding. Define Save, Discard, Back and restart behavior.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Navigation and state — knowledge check
Apply the lesson concepts to the following scenarios.
Which API navigates to a Shell route?
Why guard repeated taps while navigation is pending?
What should a dirty flag compare?
What is Preferences appropriate for?
Can a lifecycle event guarantee a final save before process termination?