Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 42 ยท MVVM and Navigation

Navigation Parameters, Tabs and Modals

Pass data between .NET MAUI pages with query strings, QueryProperty, IQueryAttributable and object parameters; show modal pages, alerts and prompts; and handle tab state, with a runnable query-parser stand-in.

A list page opens a detail page: how does the detail page know which product to show? Pages are created by the framework, so you cannot just call a constructor with arguments. MAUI Shell offers several ways to pass data, and this lesson compares them. It also covers screens that sit on top of the current page (modal pages and dialogs) and the state of tabs.

Shell and pages cannot run on this site, so the MAUI code is read-only. The query-string handling is ordinary C# string work, so it is shown with a labelled stand-in that behaves like Shell's parameter parsing.

Way 1: query strings

You can append values to the route just like on a web page:

C#
await Shell.Current.GoToAsync($"details?id={product.Id}&source=search");

The receiving page declares which parameters it accepts with QueryProperty:

C#
[QueryProperty(nameof(ProductId), "id")]
[QueryProperty(nameof(Source), "source")]
public partial class ProductDetailPage : ContentPage
{
    public string ProductId { get; set; } = "";
    public string Source { get; set; } = "";
}

Shell sets the properties after the constructor and before the page appears. Values arrive as strings and are decoded (Shell URL-decodes them), so a name such as Fish & Chips must be escaped with Uri.EscapeDataString when you build the URI. Never send secrets or large data in a query string; send an id and load the data in the destination.

On a view model the attribute works the same way, and you can put it on the class that is the page's BindingContext:

C#
[QueryProperty(nameof(ProductId), "id")]
public partial class ProductDetailViewModel : ObservableObject
{
    [ObservableProperty] private string productId = "";

    partial void OnProductIdChanged(string value) => _ = LoadAsync(value);
}

Because the property is set when the query arrives, load data in the change handler (or in OnNavigatedTo), not in the constructor.

C# Stand-in: building and parsing a query string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Way 2: object parameters with a dictionary

To pass a whole object, use the overload that takes a dictionary. It stays in memory (nothing is put in the URI):

C#
await Shell.Current.GoToAsync("details", new Dictionary<string, object>
{
    ["Product"] = product,
});
C#
[QueryProperty(nameof(Product), "Product")]
public partial class ProductDetailPage : ContentPage
{
    public Product Product { get; set; } = null!;
}

This is convenient, but the page now depends on the data being passed, and a deep link or a restore after the system killed the app has no object to give. Prefer ids for anything that can be re-opened from outside, and object parameters for short-lived, in-app flows.

Way 3: IQueryAttributable

Implementing IQueryAttributable on the page or view model receives all parameters in one method, which avoids one property per key and lets you convert types:

C#
public class ProductDetailViewModel : ObservableObject, IQueryAttributable
{
    public Product? Product { get; private set; }

    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        if (query.TryGetValue("Product", out var p) && p is Product product)
        {
            Product = product;
            OnPropertyChanged(nameof(Product));
        }
        else if (query.TryGetValue("id", out var id) && int.TryParse(id?.ToString(), out var number))
        {
            _ = LoadByIdAsync(number);
        }
    }
}

Shell clears the passed dictionary on the way back (so that the old values do not linger); if you must keep them, copy them first.

Returning data to the previous page

Shell has no built-in "result" value. The usual options are:

  • A shared service (singleton) both view models use, such as a SelectedAddressStore.
  • WeakReferenceMessenger from the Community Toolkit: the detail page sends new AddressChosen(address), the previous view model listens.
  • A TaskCompletionSource<T> passed in the parameter dictionary: the opener awaits it and the closed page sets the result. It makes a modal page feel like an awaited function call.

A modal page covers the whole screen and has its own navigation stack; you must close it to return. It is right for focused tasks such as sign-in, compose, or an image picker. With a Shell app you can mark a page as modal by registering it normally and setting Shell.PresentationMode on the page:

XML
<ContentPage x:Class="ShopApp.Views.SignInPage"
             Shell.PresentationMode="ModalAnimated">

and navigate with GoToAsync("signin") as usual. Other modes are Animated, NotAnimated, Modal, ModalAnimated and ModalNotAnimated. Without Shell you use Navigation.PushModalAsync(page) and Navigation.PopModalAsync(). Pressing the Android back button closes the modal page first.

Alerts, prompts and action sheets

For quick questions you do not need a page: Page has three built-in dialogs.

C#
await DisplayAlert("Delete", "Remove this item?", "Delete", "Cancel");           // returns bool
string? name = await DisplayPromptAsync("Rename", "New name:", initialValue: "Draft");
string? choice = await DisplayActionSheet("Share via", "Cancel", null, "Email", "Message", "Copy link");

From a view model, reach the page through Shell.Current.DisplayAlert(...) or, better, hide it behind an IDialogService so tests can fake it. Do not call DisplayAlert from a constructor, because no page is on screen yet. The Community Toolkit adds a Popup control, snackbars and toasts for light, non-blocking feedback.

Tabs and their state

Each Tab in a TabBar keeps its own navigation stack. If the user pushes details in the Home tab, switches to Cart and back, the details page is still there. Tapping the active tab icon again pops to that tab's root. To jump to another tab from code use an absolute route such as //cart. To show a number on a tab (an unread count) there is no built-in badge in Shell on all platforms; the usual solutions are custom renderers/handlers or a Toolkit badge extension.

Pages inside tabs are created lazily and kept alive while the app runs, so OnAppearing (not the constructor) is the place to refresh data that can change while another tab is open.

Passing data to the next page

Query string Simple strings such as ids
Dictionary Whole objects, in memory only
IQueryAttributable One method, all parameters

Send an id when the screen must work from a deep link.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why prefer an id over a whole object in a navigation parameter for a detail page?

    An id can travel in a URI and be re-used when the app is restored or opened from a link; a passed object exists only in memory.
  2. 2. When does Shell set QueryProperty values?

    Properties are populated once the page exists, so load data in a change handler or OnNavigatedTo, not in the constructor.
  3. 3. Which method shows a yes/no question without creating a page?

    DisplayAlert shows a platform dialog and returns a bool for a two-button alert.
  4. 4. What happens to a tab's navigation stack when the user switches to another tab and back?

    Every Tab keeps its own stack of pages, so the user returns to where they left off.

Summary

  • Pass simple data in the query string (read with QueryProperty), objects in a dictionary, or take all values in IQueryAttributable.
  • Values arrive after construction: load data in a change handler or OnNavigatedTo.
  • Return results with a shared service, a messenger or a TaskCompletionSource.
  • Modal pages and the built-in alert, prompt and action-sheet dialogs cover "on top of this page" screens.
  • Each tab keeps its own stack; refresh on OnAppearing.

Next: Loading State, Errors and Async View Models