/shiny-maui-shell:shiny-maui-shellfrom shiny-maui-shell
Generates .NET MAUI Shell pages, ViewModels, navigation, and source-generated routes using Shiny MAUI Shell. Handles deep links, app shortcuts, tab badges, and navigation interceptors.
Ships in shiny-maui-shell. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are an expert in Shiny MAUI Shell, a library that enhances .NET MAUI Shell with ViewModel lifecycle management, navigation services, source generation, tab badges, and XAML-triggered navigation.
Invoke this skill when the user wants to:
INavigatorNavigate.* attached propertiesINavigationBuilder (push multiple pages, pop-and-push)IDialogs[ShellMap] and [ShellProperty] attributesMicrosoft.Extensions.AI with route discovery and NavigateToRoute[ShellMap] and [ShellProperty] attributesDocumentation: https://shinylib.net/maui
GitHub: https://github.com/shinyorg/mauishell
NuGet: Shiny.Maui.Shell
Namespace: Shiny
Shiny MAUI Shell wraps .NET MAUI Shell to provide:
INavigator service for all navigation operationsIDialogs service for alert, confirm, prompt, and action sheet dialogsINavigationBuilder for multi-segment navigation (push multiple pages in one operation, pop-and-push)INavigator.SetTabBadge* / ClearTabBadge*, on MAUI 11 BaseShellItem.BadgeTextToolbarItem.BadgeText to the ViewModelNavigate.Route, Navigate.RelativeNavigation, and parameter helpersINavigationInterceptor guards that can cancel or redirect any navigation - including app links, shortcuts and tab tapsShinyShell base class for deterministic initial-page BindingContext assignmentShellServices record that aggregates INavigator and IDialogs for convenient single-parameter injectionIDialogs implementation via UseDialogs<TDialog>() — swap in your own dialog provider (e.g. ACR UserDialogs, a custom sheet, a test double)Inspired by Prism Library by Dan Siegel and Brian Lagunas.
dotnet add package Shiny.Maui.Shell
Manual registration:
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseShinyShell(x => x
.Add<MainPage, MainViewModel>(registerRoute: false)
.Add<DetailPage, DetailViewModel>("Detail")
.Add<SettingsPage, SettingsViewModel>("Settings")
)
.ConfigureFonts(fonts =>
{
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
});
return builder.Build();
}
With source generation (preferred):
builder
.UseMauiApp<App>()
.UseShinyShell(x => x
.AddGeneratedMaps()
.AddAiTools() // registers AiMauiShellTools as singleton for AI integration
)
With a custom dialog provider:
builder
.UseMauiApp<App>()
.UseShinyShell(x => x
.AddGeneratedMaps()
.UseDialogs<MyCustomDialogs>() // register a custom IDialogs implementation
);
UseDialogs<TDialog>() replaces the default ShellDialogs provider. The default registration uses TryAddSingleton, so a UseDialogs<> call always wins.
Built-in alternative providers (same IDialogs interface — no ViewModel changes):
// Owned, animated, themeable dialogs via Shiny.Maui.Controls (package: Shiny.Maui.Shell.ShinyDialogs)
builder
.UseMauiApp<App>()
.UseShinyControls() // registers the Controls IDialogService
.UseShinyShell(x => x
.AddGeneratedMaps()
.UseShinyDialogs() // IDialogs -> Controls dialog service
.UseShinyDialogPresenter() // ShowDialog -> overlay card (optional, see 6a)
);
// Styled UXDivers popups (package: Shiny.Maui.Shell.UxDiversDialogs)
builder
.UseMauiApp<App>()
.UseShinyShell(x => x
.AddGeneratedMaps()
.UseUxDiversDialogs() // IDialogs -> UXDivers popups
.UseUxDiversDialogPresenter() // ShowDialog -> UXDivers popup (optional, see 6a)
);
Either UXDivers call initializes the popup infrastructure (UseUXDiversPopups()) itself — do NOT
also call builder.UseUXDiversPopups(), and calling both Shiny extensions initializes it once.
ShinyShellYour AppShell (or any Shell subclass) must inherit from Shiny.ShinyShell instead of Shell. This ensures the initial page's BindingContext is set deterministically via Shell's own OnNavigated lifecycle.
AppShell.xaml:
<shiny:ShinyShell
x:Class="MyApp.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:shiny="clr-namespace:Shiny;assembly=Shiny.Maui.Shell"
xmlns:local="clr-namespace:MyApp"
Title="MyApp">
<ShellContent
Title="Home"
ContentTemplate="{DataTemplate local:MainPage}"
Route="MainPage" />
</shiny:ShinyShell>
AppShell.xaml.cs:
using Shiny;
namespace MyApp;
public partial class AppShell : ShinyShell
{
public AppShell()
{
InitializeComponent();
}
}
registerRoute: false since Shell already registers themWhen generating code for Shiny MAUI Shell projects, follow these conventions:
All ViewModels must implement INotifyPropertyChanged. Use CommunityToolkit.Mvvm ObservableObject as the base:
[ShellMap<MyPage>("MyRoute")]
public partial class MyViewModel : ObservableObject
{
}
[ShellMap<TPage>("Route")] on every ViewModel classroute parameter must be a valid C# identifier — it is used as the generated constant name and method namePage suffix is used as the generated nameregisterRoute: false only for pages already declared in AppShell.xamlpartialINavigator and other dependenciesUse [ShellProperty] on ViewModel properties that should be passed as navigation parameters:
[ShellMap<DetailPage>("Detail")]
public partial class DetailViewModel : ObservableObject
{
[ShellProperty]
public string ItemId { get; set; }
[ShellProperty(required: false)]
public int PageIndex { get; set; }
}
[ShellProperty] are required by default[ShellProperty(required: false)] for optional parametersstring? sort = null); leaving the argument out keeps the viewmodel's own initializer rather than assigning null. Value types default to default and are always assigned[ShellProperty] properties are set directly by the source-generated navigation methods — no IQueryAttributable neededINavigatorImplement these interfaces on ViewModels as needed:
| Interface | Purpose |
|---|---|
IPageLifecycleAware | OnAppearing() / OnDisappearing() hooks |
INavigationConfirmation | Task<bool> CanNavigate() - confirm before leaving. Only asked for user-driven Shell navigation (tab tap, flyout, hardware back), not for INavigator calls - use an INavigationInterceptor to guard those |
INavigationAware | OnNavigatingFrom(IDictionary<string, object>) - mutate args before leaving |
IQueryAttributable | ApplyQueryAttributes(IDictionary<string, object>) - receive navigation args (only needed for string-based NavigateTo(route, args) — not needed when using [ShellProperty]) |
IDisposable | Cleanup when page is removed from navigation stack |
INavigator exposes two events for observing navigation:
Navigating — fires before navigation with the source ViewModel instanceNavigated — fires after navigation with the destination ViewModel instancenavigator.Navigating += (sender, args) =>
{
// args.FromUri, args.FromViewModel, args.ToUri, args.NavigationType, args.Parameters
};
navigator.Navigated += (sender, args) =>
{
// args.ToUri, args.ToViewModel, args.NavigationType, args.Parameters
};
Hook these events in an IMauiInitializeService for cross-cutting concerns like logging or analytics.
They only fire for navigation Shiny performs. To observe every navigation - including tab taps,
flyout items and the back button Shell handles itself, app links and shortcuts - and how each one
ended, implement INavigationObserver instead. Never add an always-continue interceptor just to
watch navigation: it switches on the interceptor pipeline (a Shell deferral, an early ViewModel
resolve) and still cannot see the outcome.
public class NavigationAnalytics : INavigationObserver
{
public void OnNavigationStarted(NavigationStarted nav) { /* nav.Id, Source, NavigationType, Uri, FromUri, FromViewModel, Parameters, ShellSource */ }
public void OnNavigationFinished(NavigationFinished r) { /* r.Navigation, Outcome (Completed|Cancelled|Redirected|Failed), Uri, Redirects, CancelledBy, Exception, Duration */ }
}
builder.UseShinyShell(x => x.AddGeneratedMaps().AddNavigationObserver<NavigationAnalytics>());
// a library: builder.Services.AddSingleton<INavigationObserver, NavigationAnalytics>();
Related observation hooks (all resolve from DI):
IRouteRegistry.Routes - every mapped route with PageType, ViewModelType, IsRegisteredWithShell,
Description and Parameters ([ShellProperty]s; null for hand-mapped routes). AddGeneratedMaps()
emits builder.AddRouteInfo(...) for each [ShellMap] - no AI extensions needed.IDialogObserver (AddDialogObserver<T>()) - OnDialogShown(PresentedDialog) /
OnDialogClosed(PresentedDialog, DialogClosed) for ShowDialog dialogs. PresentedDialog.TryComplete(value)
and TryCancel() answer a dialog from code (tests, automation). DialogObservers.Open lists open dialogs.ShellTabBadgeManager.Values / Get(route) - read back badge text ("" = dot, null = none).Use INavigationInterceptor when navigation must be blocked or rerouted - auth guards, unsaved
changes, feature flags. Use the Navigating/Navigated events when you only need to observe.
public class AuthNavigationInterceptor(IAuthService auth) : INavigationInterceptor
{
public int Order => -100; // guards before observers; ties keep registration order
public async Task<NavigationInterceptorResult> InterceptNavigationAsync(
string uri,
object? viewModel,
CancellationToken cancellationToken
)
{
if (await auth.IsAuthorized(cancellationToken) || uri.Contains("Login"))
return NavigationInterceptorResult.Continue;
return NavigationInterceptorResult.Redirect<LoginViewModel>();
}
}
Register in MauiProgram.cs - they run in registration order, first to cancel or redirect wins:
builder.UseShinyShell(x => x
.AddGeneratedMaps()
.AddNavigationInterceptor<AuthNavigationInterceptor>()
.AddNavigationInterceptor<AuditNavigationInterceptor>()
// inline for one-liners
.AddNavigationInterceptor((uri, vm, ct) => Task.FromResult(NavigationInterceptorResult.Continue), order: 100)
);
Results:
| Result | Behaviour |
|---|---|
NavigationInterceptorResult.Continue | Next interceptor, then navigate |
Cancel() | Nothing navigates; the caller's Task completes normally |
Redirect("Detail") | Push |
Redirect("//Main/Home") / Redirect("/Login") | Reset the stack (single leading / is promoted to //) |
Redirect<LoginViewModel>() | Reset the stack to that ViewModel's route - prefer this, it is refactor-safe |
Redirect<DetailViewModel>(relativeNavigation: true) | Push that ViewModel's route |
Rules to generate correctly:
viewModel argument is the destination ViewModel, already resolved and populated
(configure callback run, app link values applied). Mutating it is allowed - that instance is
bound to the page, except on a registerRoute: false (ShellContent) page that is already
realised, which keeps the ViewModel it already has. It is null for unmapped routes and for Shell-driven navigation (tab taps,
hardware back), so always null-check or pattern-match: if (viewModel is DetailViewModel vm).INavigationContextAccessor.Current.FromViewModel -
inject INavigationContextAccessor for that, plus FromUri, ToUri, NavigationType,
Parameters, RedirectCount.INavigator calls, the navigation builder, back navigation, app links, app
shortcuts and user-driven Shell navigation. They do not cover ShowDialog or SwitchShell.Order (lowest first) then registration order. Put guards below 0 and observers above.INavigator navigation method returns Task<bool> - false means an interceptor cancelled
it (a redirect returns true). Generated NavigateTo{Route} methods return Task<bool> too.bypassInterceptors: true: NavigateTo<LoginViewModel>(bypassInterceptors: true),
GoBack(1, bypassInterceptors: true), PopToRoot(bypassInterceptors: true),
CreateBuilder()...Navigate(bypassInterceptors: true) or the fluent
CreateBuilder().BypassInterceptors()...Navigate(). A RedirectUri does not need it.INavigationContextAccessor.Current.Direction gives Forward / Back / Root when the rule
only cares which way the user is going; .GetDirection() converts any NavigationType.AppLinkResult.Blocked from IAppLinks.Handle
(distinct from Unhandled, which means nothing matched).IDialogs.Confirm / ActionSheet) - the
navigation waits on the answer. Treat a dismissed sheet (which returns the cancel text) as
Cancel(), and always narrow to the destination being guarded first.// Unsaved-changes guard: uses the page being left, not the destination
public class UnsavedChangesInterceptor(
INavigationContextAccessor context,
IDialogs dialogs
) : INavigationInterceptor
{
public async Task<NavigationInterceptorResult> InterceptNavigationAsync(
string uri,
object? viewModel,
CancellationToken cancellationToken
)
{
if (context.Current?.FromViewModel is not IUnsavedChanges { HasUnsavedChanges: true })
return NavigationInterceptorResult.Continue;
return await dialogs.Confirm("Unsaved Changes", "Discard changes?")
? NavigationInterceptorResult.Continue
: NavigationInterceptorResult.Cancel();
}
}
// One action sheet, all three outcomes - a dialog is awaitable here because the navigation has
// not been handed to Shell yet
public class AskFirstInterceptor(IDialogs dialogs) : INavigationInterceptor
{
const string LetItGo = "Let it through";
const string SendElsewhere = "Go to Settings instead";
const string StopIt = "Stop navigation";
public async Task<NavigationInterceptorResult> InterceptNavigationAsync(
string uri,
object? viewModel,
CancellationToken cancellationToken
)
{
if (viewModel is not DetailViewModel) // always narrow, or tab taps prompt too
return NavigationInterceptorResult.Continue;
var choice = await dialogs.ActionSheet(
$"Navigating to '{uri}'",
cancel: StopIt, // a dismissed sheet returns the cancel text
destruction: null,
buttons: [LetItGo, SendElsewhere]
);
return choice switch
{
LetItGo => NavigationInterceptorResult.Continue,
SendElsewhere => NavigationInterceptorResult.Redirect<SettingsViewModel>(relativeNavigation: true),
_ => NavigationInterceptorResult.Cancel() // cancel, dismissed or unknown
};
}
}
Always use INavigator for navigation, never Shell.Current.GoToAsync directly:
// Route-based navigation with args
await navigator.NavigateTo("Detail", args: [("ItemId", "123"), ("PageIndex", 0)]);
// ViewModel-based navigation with strongly-typed configuration
await navigator.NavigateTo<DetailViewModel>(vm => vm.ItemId = "123");
// Source-generated strongly-typed method (preferred)
await navigator.NavigateToDetail("123", pageIndex: 0);
// Absolute navigation (navigates to root route "//Detail")
await navigator.NavigateTo("Detail", relativeNavigation: false);
await navigator.NavigateTo<DetailViewModel>(relativeNavigation: false);
// Go back with result parameters
await navigator.GoBack(("Result", selectedItem));
// Go back multiple pages
await navigator.GoBack(backCount: 2);
// Pop to root
await navigator.PopToRoot();
// Switch to a different Shell instance
await navigator.SwitchShell(new MainAppShell());
// Switch to a Shell resolved from DI
await navigator.SwitchShell<MainAppShell>();
Use INavigationBuilder for multi-segment navigation (pushing multiple pages in a single operation):
// Push a chain of pages: One > Another > Two
await navigator
.CreateBuilder()
.Add<OneViewModel>(x => x.Text = "First")
.Add<AnotherViewModel>(x => x.Arg = "Middle")
.Add<TwoViewModel>(x => x.Text = "Last")
.Navigate();
// Pop back 2 pages, then push a new page
await navigator
.CreateBuilder()
.PopBack(2)
.Add<OneViewModel>(x => x.Text = "Replaced")
.Navigate();
// Add by route name (no configure callback)
await navigator
.CreateBuilder()
.Add("Detail")
.Navigate();
Important Shell constraints for the Navigation Builder:
Routing.RegisterRoute (i.e., registerRoute: true, which is the default). Pages declared as ShellContent in XAML cannot be used in multi-segment relative URIs.PopBack() must be called before any Add() calls.fromRoot: true on CreateBuilder only works when the target route is a shell-declared route (a ShellContent in XAML), not a globally registered route.Use the badge APIs when a route already exists as a tab in the active Shell:
// Route-based badge updates
await navigator.SetTabBadge("Inbox", 3);
await navigator.ClearTabBadge("Inbox");
// ViewModel-based badge updates
await navigator.SetTabBadge<InboxViewModel>(7);
await navigator.ClearTabBadge<InboxViewModel>();
// Text, or "" for a dot
await navigator.SetTabBadge("Inbox", "New");
await navigator.SetTabBadge<InboxViewModel>("");
BadgeText on the tab's ShellSection - rendered on Android, iOS, Mac Catalyst, Windows (non-numeric text is a dot there); no-op elsewhere, never throws PlatformNotSupportedExceptionBadgeColor / BadgeTextColor on the Tab. Do not generate color parameters for SetTabBadgeBadgeText in XAML on a tab that is also driven by SetTabBadgeToolbar badges are not an INavigator API: bind ToolbarItem.BadgeText to a ViewModel property (string? - null hides, "" is a dot):
<ContentPage.ToolbarItems>
<ToolbarItem Text="Inbox"
Command="{Binding OpenInboxCommand}"
BadgeText="{Binding UnreadCount}"
BadgeColor="Red" />
</ContentPage.ToolbarItems>
Use Navigate.* attached properties for simple route-based navigation directly from XAML:
<ContentPage
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:shiny="clr-namespace:Shiny;assembly=Shiny.Maui.Shell">
<ContentPage.ToolbarItems>
<ToolbarItem Text="Home"
shiny:Navigate.Route="MainPage"
shiny:Navigate.RelativeNavigation="False" />
</ContentPage.ToolbarItems>
<Button Text="Open Detail"
shiny:Navigate.Route="Detail"
shiny:Navigate.ParameterKey="ItemId"
shiny:Navigate.ParameterValue="{Binding SelectedId}" />
</ContentPage>
For multiple parameters:
<Button Text="Open Modal"
shiny:Navigate.Route="Modal">
<shiny:Navigate.Parameters>
<shiny:NavigationParameters>
<shiny:NavigationParameter Key="Arg1" Value="{Binding NavArg}" />
<shiny:NavigationParameter Key="Arg2" Value="5" />
</shiny:NavigationParameters>
</shiny:Navigate.Parameters>
</Button>
Button, MenuItem, ToolbarItemNavigate.Route accepts the route string passed to INavigator.NavigateTo(...)Shiny MAUI Shell generates AI-compatible route metadata and navigation methods for use with Microsoft.Extensions.AI. An AI chat client can discover routes, understand their purpose, and navigate with parameters extracted from natural language.
Describe routes for AI — Add description to [ShellMap] and [ShellProperty]:
public enum WorkOrderPriority { Low, Medium, High, Urgent }
[ShellMap<WorkOrderPage>(description: "Use when the user reports something broken or needing repair")]
public partial class WorkOrderViewModel : ObservableObject
{
[ShellProperty("Summarize what is broken based on what the user said", required: true)]
public string Description { get; set; } = string.Empty;
[ShellProperty("Infer urgency from tone. Must be: Low, Medium, High, or Urgent", required: true)]
public WorkOrderPriority Priority { get; set; } = WorkOrderPriority.Medium;
}
Generated AI class (AiMauiShellTools):
The source generator produces an AiMauiShellTools class (name configurable via ShinyMauiShell_AiToolsClassName) that takes INavigator via constructor injection and provides:
Prompt — pre-formatted string describing all AI-applicable routes for seeding AI system messagesTools — ready-to-use AITool[] instances for route discovery and navigationGetAiToolApplicableGeneratedRoutes() — returns only routes that have a description AND at least one parameterNavigateToRoute(route, args) — AI-friendly navigation using switch dispatch to NavigateTo<TViewModel> with direct property setters and automatic type conversion (int, bool, double, enums, DateTime, etc.)Additionally, GetGeneratedRouteInfo() remains as a static extension on INavigator returning all routes with parameter metadata.
A generated AddAiTools() extension on ShinyAppBuilder registers the class as a singleton.
Wire up AI tools (opt-in: set ShinyMauiShell_GenerateAiExtensions to true and reference Microsoft.Extensions.AI):
// MauiProgram.cs
builder.UseShinyShell(x => x
.AddGeneratedMaps()
.AddAiTools()
);
// In your ViewModel — inject AiMauiShellTools
public class ChatViewModel(AiMauiShellTools aiTools)
{
var options = new ChatOptions { Tools = [.. aiTools.Tools] };
}
Key conventions for AI-friendly ViewModels:
GetAiToolApplicableGeneratedRoutes (not GetGeneratedRouteInfo) to keep the AI focused on actionable routesstring, int, bool, double, enums, DateTime, Guid, etc. — the generated NavigateToRoute handles type conversion automaticallyDeclare inbound URL templates in the appLinks argument of [ShellMap] - never a separate attribute:
[ShellMap<ProductPage>(
description: "Shows a product",
appLinks: ["product/{id}", "p/{id}"]
)]
public partial class ProductViewModel : ObservableObject
{
[ShellProperty("The product id")] public int Id { get; set; }
[ShellProperty(required: false)] public string? Tab { get; set; }
}
Wire it up once:
<PropertyGroup>
<ShinyAppLinkSchemes>myapp</ShinyAppLinkSchemes>
<ShinyAppLinkDomains>shinylib.net</ShinyAppLinkDomains>
</PropertyGroup>
.UseShinyShell(x => x.AddGeneratedMaps())
AddGeneratedMaps() installs everything declared on [ShellMap] - routes, app links and app
shortcuts. There is no separate opt-in call.
Rules to follow when generating app link code:
{token} names must match a [ShellProperty] name (case-insensitive) or the build fails with
SHINY005. Query values bind by property name too.navigationRoot or nav-mode argument - push vs. reset is inferred from
registerRoute. registerRoute: false (a ShellContent in AppShell XAML) resets to //route;
registerRoute: true pushes.Application subclass, an AppDelegate OpenUrl
override, or a MainActivity OnNewIntent override. AddGeneratedMaps() installs all of it.
UseAppLinks(o => ...) is optional and only changes AppLinkOptions defaults.[IntentFilter] on MainActivity for Android, CFBundleURLTypes in
Info.plist and com.apple.developer.associated-domains in Entitlements.plist for Apple.Create{Route}AppLink(...), not string concatenation.
It is only generated when exactly one scheme (or one domain, with no scheme) is configured.Optional tuning:
.UseShinyShell(x => x
.AddGeneratedMaps()
.UseAppLinks(o =>
{
o.DefaultRoot = "//main/home"; // back stack for cold-start pushes
o.ResolveRoute = match => "//custom"; // overrides the registerRoute inference
o.OnUnhandled = uri => Task.FromResult(false);
})
)
Declared with named properties on [ShellMap] - there is no separate attribute:
[ShellMap<SearchPage>(
Shortcut = "Search",
ShortcutSubtitle = "Find anything",
ShortcutIcon = "search",
ShortcutOrder = 0
)]
public partial class SearchViewModel : ObservableObject { }
.UseShinyShell(x => x.AddGeneratedMaps())
Rules to follow when generating app shortcut code:
Shortcut (the title) is the trigger. Setting ShortcutSubtitle/ShortcutIcon/ShortcutOrder
without it is a SHINY012 error - nothing would be declared.[ShellProperty] cannot declare a shortcut (SHINY010). Use
builder.AddAppShortcut<TViewModel>(title, configure: vm => vm.X = ..., id: "...") instead.AddGeneratedMaps() installs shortcuts. MAUI's AppActions handles delivery; do not
hand-write UIApplicationShortcutItem, ShortcutManagerCompat,
ConfigureEssentials/AddAppAction, or an OnAppAction switch.registerRoute,
same as app links.AddAppShortcut<TViewModel> is the public API the generator emits calls to; it is also how to
use shortcuts when source generation is disabled.IAppShortcutText and register it with
UseShortcutText<T>() - the declared string becomes the resource key. Do not try to localize by
putting CultureInfo logic in the attribute; attribute arguments are compile-time constants.
After a language change call IAppShortcuts.Refresh(), or the installed text stays stale.Always use IDialogs for user-facing dialogs. Inject it via the primary constructor:
public class MyViewModel(INavigator navigator, IDialogs dialogs)
{
// Alert - informational message
await dialogs.Alert("Title", "Something happened");
// Confirm - yes/no question, returns bool
bool confirmed = await dialogs.Confirm("Delete?", "Are you sure?");
// Prompt - text input, returns string? (null if cancelled)
var name = await dialogs.Prompt("Name", "Enter your name", placeholder: "John Doe");
// Prompt with numeric keyboard
var age = await dialogs.Prompt("Age", "Enter your age", keyboard: Keyboard.Numeric);
// Action sheet - choose from options
var choice = await dialogs.ActionSheet("Options", "Cancel", "Delete", "Edit", "Share");
}
Use IDialogs for alert / confirm / prompt / action sheet. When the dialog needs real UI — a picker,
a filter sheet, a form — build a normal Page + ViewModel pair, have the ViewModel implement
IDialogAware<T>, and await it with the generated Show{Route}Dialog extension.
ViewModel — implement IDialogAware<T> with two events. Do NOT introduce a base class; the
ViewModel's base slot belongs to ObservableObject.
[ShellMap<PickColorPage>("PickColor")]
public partial class PickColorViewModel : ObservableObject, IDialogAware<string>
{
public event EventHandler<string>? Completed;
public event EventHandler? Cancelled;
[ShellProperty("The colour to pre-select", required: false)]
public string Preset { get; set; } = "Red";
[RelayCommand] void Pick(string colour) => this.Completed?.Invoke(this, colour);
[RelayCommand] void Cancel() => this.Cancelled?.Invoke(this, EventArgs.Empty);
}
Call site — always prefer the generated extension. It infers both type arguments and turns
[ShellProperty] values into method parameters:
var result = await navigator.ShowPickColorDialog(preset: "Violet");
if (result.TryGetValue(out var colour))
this.Selected = colour;
// or, with a fallback
this.Selected = result.ValueOr("Red");
The underlying method needs both type arguments spelled out, because C# cannot infer a type argument
from a constraint — only reach for it when there is no [ShellMap] on the ViewModel:
var result = await navigator.ShowDialog<PickColorViewModel, string>(x => x.Preset = "Violet");
Rules:
[ShellMap<TPage>]
AddGeneratedMaps(), or ShinyAppBuilder.Add<TPage, TViewModel>(). It throws otherwise.DialogResult<T> — check IsCancelled, or use TryGetValue(out var v) / ValueOr(fallback).
Never assume Value is meaningful without checking; default(T) cannot represent cancellation for
value types.DialogResult<T>. The passed
CancellationToken firing throws OperationCanceledException — these are different things.Shell.PresentationMode="Modal" — the default presenter pushes it modally.IPageLifecycleAware.OnAppearing/OnDisappearing and IDisposable.Dispose all fire on
the dialog ViewModel, and with the default modal presenter the page underneath gets OnDisappearing
when the dialog opens and OnAppearing when it closes. INavigationAware, INavigationConfirmation
and the Navigating/Navigated events are deliberately NOT involved — a dialog is not a stack mutation.ShowDialog returns. The
returned DialogResult<T> is unaffected, but do not use the ViewModel instance after the await.Changing presentation — the ViewModel, IDialogAware<T> and the call site never change; only the
registered IDialogPresenter does.
| Presenter | Package | Registration | Presentation |
|---|---|---|---|
ShellModalDialogPresenter (default) | Shiny.Maui.Shell | — | Page on Shell's modal stack |
ShinyOverlayDialogPresenter | Shiny.Maui.Shell.ShinyDialogs | UseShinyDialogPresenter() | Themed card over a dimmed backdrop, inside the current page |
UxDiversDialogPresenter | Shiny.Maui.Shell.UxDiversDialogs | UseUxDiversDialogPresenter() | UXDivers PopupPage over a dimmed backdrop |
builder.UseShinyShell(x => x
.AddGeneratedMaps()
.UseShinyDialogPresenter(o => // or .UseUxDiversDialogPresenter(o => ...)
{
o.BackdropOpacity = 0.6; // both: BackdropOpacity, BackdropColor, DismissOnBackdropTap,
o.CornerRadius = 24; // CornerRadius, CardBackgroundColor, MaxWidth, Margin,
o.MaxWidth = 480; // AnimationDuration
})
);
Both overlay presenters take the dialog page's Content, so the dialog page must be a ContentPage
with content set — they throw otherwise. The page underneath stays on screen behind the scrim, so it
does NOT get OnDisappearing/OnAppearing around the dialog; the dialog ViewModel's own hooks are
unchanged. A backdrop tap (or, for the overlay presenter, the host page disappearing) reports
IsCancelled.
Writing your own — implement IDialogPresenter for a host that takes a Page. Its task must
complete when the page is gone (user-dismissed or dismiss fired), and must not throw
OperationCanceledException on dismiss:
builder.UseShinyShell(x => x
.AddGeneratedMaps()
.UseDialogPresenter<MyPopupPresenter>()
);
For a host that takes a View (popup / bottom sheet / overlay), derive from ViewDialogPresenter
instead of implementing the interface directly — it unwraps the page, sets the binding context, raises
IPageLifecycleAware, disposes the ViewModel and restores the content afterwards:
public class MySheetPresenter : ViewDialogPresenter
{
// called on the main thread; detach `content` from your host before returning
protected override async Task PresentView(View content, object viewModel, CancellationToken dismiss)
=> /* show content, complete when it is gone */;
}
ShellServices is a convenience record that bundles the shell services together. Inject it when a ViewModel or service needs both and you want a single parameter:
public record ShellServices(
INavigator Navigator,
IDialogs Dialogs
);
public class MyViewModel(ShellServices shell)
{
async Task DoWork()
{
await shell.Dialogs.Alert("Done", "Work complete");
await shell.Navigator.GoBack();
}
}
ShellServices is registered as a singleton by UseShinyShell() — no extra setup required.
For main-thread marshalling use MAUI's own MainThread (Microsoft.Maui.ApplicationModel). Shiny Shell has no thread abstraction of its own (IMainThread was removed in v8) — never generate IMainThread, MauiMainThread or shell.MainThread.
Set Shell.PresentationMode="Modal" on the page XAML:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
Shell.PresentationMode="Modal"
x:Class="MyApp.ModalPage">
Navigate to it like any other page. Close with GoBack().
If the modal exists to collect a value from the user, prefer §6a instead — ShowDialog presents it
modally for you and hands back a typed result.
Place files following standard MAUI conventions:
Views/{Name}Page.xaml + Views/{Name}Page.xaml.csViewModels/{Name}ViewModel.csFeatures/{Feature}/{Name}Page.xaml + {Name}ViewModel.csThe source generator produces several files from [ShellMap] and [ShellProperty] attributes. Each can be individually disabled via MSBuild properties.
The constant name is derived from the route parameter (or page type name without Page suffix when no route is specified):
public static class Routes
{
public const string Detail = "Detail";
public const string Settings = "Settings";
}
Method names are also derived from the route parameter:
public static class NavigationExtensions
{
public static Task NavigateToDetail(this INavigator navigator, string itemId, int pageIndex = default)
{
return navigator.NavigateTo<DetailViewModel>(x =>
{
x.ItemId = itemId;
x.PageIndex = pageIndex;
});
}
}
Only emitted for [ShellMap] ViewModels that also implement IDialogAware<T>. Not generated at all when there are none, and never added to the AI tool surface:
public static class DialogExtensions
{
public static Task<DialogResult<string>> ShowPickColorDialog(this INavigator navigator,
string? preset = null,
CancellationToken cancellationToken = default)
{
return navigator.ShowDialog<PickColorViewModel, string>(x => { if (preset is not null) x.Preset = preset; }, cancellationToken);
}
}
Uses inline string literals (not Routes.* constants), so it works regardless of whether route constants are enabled:
public static class NavigationBuilderExtensions
{
public static ShinyAppBuilder AddGeneratedMaps(this ShinyAppBuilder builder)
{
builder.Add<DetailPage, DetailViewModel>("Detail");
builder.Add<SettingsPage, SettingsViewModel>("Settings");
return builder;
}
}
Generated only when appLinks templates exist and exactly one scheme (or one domain, with no
scheme) is configured - otherwise there is no single correct base URL to build against.
var uri = navigator.CreateProductAppLink(id: 42, tab: "reviews");
// myapp://product/42?Tab=reviews
App link registrations are also appended to AddGeneratedMaps() as builder.AddAppLink<TViewModel>(...)
calls carrying a source-generated binder - never call AddAppLink by hand.
Disable individual generated files via MSBuild properties in .csproj:
<PropertyGroup>
<!-- Disable Routes.g.cs -->
<ShinyMauiShell_GenerateRouteConstants>false</ShinyMauiShell_GenerateRouteConstants>
<!-- Disable NavigationExtensions.g.cs and DialogExtensions.g.cs -->
<ShinyMauiShell_GenerateNavExtensions>false</ShinyMauiShell_GenerateNavExtensions>
<!-- Enable AI extensions (opt-in, requires Microsoft.Extensions.AI) -->
<ShinyMauiShell_GenerateAiExtensions>true</ShinyMauiShell_GenerateAiExtensions>
<!-- Customize the generated AI tools class name (default: AiMauiShellTools) -->
<ShinyMauiShell_AiToolsClassName>MyAppAiTools</ShinyMauiShell_AiToolsClassName>
<!-- Customize the generated static extensions class name (default: AiExtensions) -->
<ShinyMauiShell_AiExtensionsClassName>MyAppRouteExtensions</ShinyMauiShell_AiExtensionsClassName>
<!-- Customize the AI navigate method name (default: NavigateToRoute) -->
<ShinyMauiShell_AiNavigateMethodName>GoToPage</ShinyMauiShell_AiNavigateMethodName>
</PropertyGroup>
| Property | Default | Controls |
|---|---|---|
ShinyMauiShell_GenerateRouteConstants | true | Routes.g.cs |
ShinyMauiShell_GenerateNavExtensions | true | All navigation extensions and AddGeneratedMaps |
ShinyMauiShell_GenerateAiExtensions | false | AiMauiShellTools class, AddAiTools(), GetAiToolApplicableGeneratedRoutes, NavigateToRoute, and Prompt. Opt-in: set to true to generate them. Requires Microsoft.Extensions.AI (SHINY003 error if missing) |
ShinyMauiShell_AiToolsClassName | AiMauiShellTools | Class name for the generated AI tools class |
ShinyMauiShell_AiExtensionsClassName | AiExtensions | Class name for the static route info extensions class |
ShinyMauiShell_AiNavigateMethodName | NavigateToRoute | Method name for the AI-friendly navigate method |
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Shiny;
namespace MyApp.ViewModels;
[ShellMap<DetailPage>("Detail")]
public partial class DetailViewModel(INavigator navigator, IDialogs dialogs) : ObservableObject,
IPageLifecycleAware,
INavigationConfirmation,
INavigationAware,
IDisposable
{
[ShellProperty]
[ObservableProperty]
string itemId;
[ObservableProperty]
string title;
bool hasUnsavedChanges;
// Page appeared
public void OnAppearing()
{
// Load data, start listening, etc.
}
// Page disappearing
public void OnDisappearing()
{
// Pause operations
}
// Confirm before leaving
public async Task<bool> CanNavigate()
{
if (!hasUnsavedChanges)
return true;
return await dialogs.Confirm(
"Unsaved Changes",
"You have unsaved changes. Discard them?"
);
}
// Mutate parameters before leaving
public void OnNavigatingFrom(IDictionary<string, object> parameters)
{
parameters["LastViewedItem"] = ItemId;
}
[RelayCommand]
async Task Save()
{
// Save logic
hasUnsavedChanges = false;
await navigator.GoBack(("Saved", true));
}
[RelayCommand]
Task GoBack() => navigator.GoBack();
public void Dispose()
{
// Cleanup subscriptions, timers, etc.
}
}
[ShellMap] + [ShellProperty] + AddGeneratedMaps() over manual registrationShell.Current.GoToAsync directly; use INavigator for testabilityShell.Current.DisplayAlert directly; use IDialogs for testability[ShellProperty] - Properties are set directly by generated navigation methods — no IQueryAttributable neededINavigationConfirmation; use INavigationInterceptor when the rule is app-wide or needs to redirect (auth, feature flags)[ShellMap] source generation and CommunityToolkit attributesNavigate.* for lightweight XAML wiring - Prefer ViewModel commands when navigation needs branching logic or validationFor detailed templates and examples, see:
reference/templates.md - Page and ViewModel code generation templatesreference/api-reference.md - Full API surface, interfaces, and attributesdotnet add package Shiny.Maui.Shell # Core library with source generators
dotnet add package CommunityToolkit.Mvvm # ObservableObject, RelayCommand, etc.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub shinyorg/mauishell --plugin shiny-maui-shell2 plugins ship this exact skill · first indexed Nov 26, 2026
Other plugins' skills for the same job