Page state and lifetime
Decide what should happen to a draft before choosing how to create a page. A counter that resets is fine in a demo; a note that disappears when the user changes tabs is usually not.
Know what your navigation host retains
| Host behavior | What survives |
|---|---|
NavigationShell, desktop |
A destination's view is created on first visit and cached for later selections. |
NavigationShell, mobile |
Each navigation call creates a new destination view. Returning Home and reopening a destination starts a fresh instance. |
NavigationView |
Pushed pages remain in the navigation stack until popped; transition work controls which page surfaces are active. |
Desktop caching is in-memory state, not persistence. Restarting the process still loses it. The mobile shell also prevents pushes during a transition, so avoid treating every rapid click as an accepted navigation.
Put durable state outside the view
A page can accept an application model in its constructor. The navigation item's factory closes over that model and creates a fresh view that displays it. The model can retain draft text or a selected record while the view owns labels, buttons, and layout.
Use stable record IDs when passing a selection, and handle a record that was deleted while another page was open. Do not pass an already-parented view as “page data.”
For a local counter, storing the count in the page is enough. For data that must survive process exit, save it through an application service; a navigation cache is not a storage layer.
Pair active work with inactive cleanup
Views expose OnActivate() and OnDeactivate() for active subscriptions, animations, and other work. Start observation when active, stop it when inactive, and allow activation to happen again. Call the base implementation when overriding either method.
OnAttach(ref AttachEventRef) and OnDetach(ref DetachEventRef) describe membership in the tree. Use them for resources whose lifetime specifically follows attachment. A view can be inactive without becoming garbage; a cached page is still referenced by its host.
A reliable subscription pattern is to acquire the source once for the active period, register one handler, then unregister that same handler during deactivation. Avoid anonymous handlers that you cannot later remove. Cancel pending asynchronous work and ignore results that arrive for an old activation.
The overlay example demonstrates cleanup in OnDeactivate(). Its overlay closes when the user leaves, even if navigation retains the page object for a future visit.