🐚 Shell Básico en .NET MAUI

El estándar moderno: navegación por rutas, AppShell.xaml y GoToAsync

📑 Contenido

  1. Introducción
  2. Shell vs NavigationPage
  3. Estructura de archivos
  4. AppShell.xaml y AppShell.xaml.cs
  5. App.xaml.cs — Configuración
  6. Páginas y rutas
  7. Navegación con GoToAsync
  8. Paso de parámetros
  9. Ejemplo práctico completo
  10. Buenas prácticas y errores comunes
  11. Resumen

1. Introducción

Shell es el contenedor de navegación moderno y recomendado de .NET MAUI. Unifica en un único archivo (AppShell.xaml) todo lo que antes requería combinar NavigationPage, TabbedPage y FlyoutPage:

🐚 Representación Visual — Shell

Contenido textual de la representación

🐚 Representación Visual — Shell

← Detalle

📄 Página de Detalle

Has llegado aquí mediante
GoToAsync("detalle")

Shell proporciona la barra de navegación automáticamente, igual que NavigationPage

📌 Idea clave: Si has entendido NavigationPage, ya tienes el 80% de Shell. La diferencia principal es que, en lugar de new DetallePage() y PushAsync, se usan rutas de texto ("detalle") registradas en AppShell.xaml.cs.

¿Cuándo usar Shell?

Situación ¿Usar Shell?
Proyecto nuevo en .NET MAUI ✅ Sí
App con tabs (pestañas) ✅ Sí
App con flyout (menú lateral) ✅ Sí
App con deep linking ✅ Sí
App sencilla de una sola sección ⚠️ Considera NavigationPage

2. Shell vs NavigationPage

Si ya entiendes NavigationPage, la forma más rápida de entender Shell es viendo la equivalencia entre sus APIs.

Concepto NavigationPage Shell
Configuración inicial new NavigationPage(new MainPage()) new AppShell() con AppShell.xaml
Abrir página (instancia) PushAsync(new DetallePage()) No aplica (Shell usa rutas)
Abrir página (ruta) No aplica GoToAsync("detalle")
Volver atrás PopAsync() GoToAsync("..")
Volver a la raíz PopToRootAsync() GoToAsync("//ruta")
Pasar parámetros Por constructor Por URI con ?param=valor
Tabs No nativo ✅ <TabBar> en AppShell.xaml
Flyout No nativo ✅ <FlyoutItem> en AppShell.xaml
Deep linking No nativo ✅ Routing.RegisterRoute

💡 Observación clave: Shell no crea instancias de páginas con new DetallePage(). En su lugar, se registra un nombre de ruta ("detalle") asociado al tipo (typeof(DetallePage)), y Shell crea la instancia automáticamente cuando navegas a esa ruta.


3. Estructura de archivos

Para usar Shell, se añaden dos archivos nuevos al proyecto: AppShell.xaml y AppShell.xaml.cs.

3. Estructura de archivos

Contenido textual de la representación

MiApp/
├── App.xaml
├── App.xaml.cs   ← Configura AppShell como MainPage
├── AppShell.xaml   ← Aquí se define la estructura visual
├── AppShell.xaml.cs   ← Aquí se registran las rutas
├── MainPage.xaml   ← Página raíz
├── MainPage.xaml.cs
├── DetallePage.xaml   ← Página a la que se navega
└── DetallePage.xaml.cs

📌 Nota: Cuando creas un proyecto .NET MAUI desde plantilla, ya viene con AppShell. Solo necesitas modificar AppShell.xaml y registrar las rutas.


4. AppShell.xaml y AppShell.xaml.cs

AppShell.xaml — Estructura visual

Aquí se define la jerarquía de páginas. El elemento más básico es <ShellContent>, que asocia un nombre (ruta) con una página.

<?xml version="1.0" encoding="utf-8" ?>
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:MiApp"
       x:Class="MiApp.AppShell"
       Shell.FlyoutBehavior="Disabled">

    <!-- Página raíz -->
    <ShellContent Title="Inicio"
                  ContentTemplate="{DataTemplate local:MainPage}"
                  Route="MainPage" />

</Shell>

AppShell.xaml.cs — Registro de rutas

Aquí se registran las rutas a las que se puede navegar. Las páginas raíz (las que están en el AppShell.xaml) no necesitan registro, pero las páginas a las que navegas desde ellas sí.

namespace MiApp;

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();

        // Registrar rutas para navegación
        Routing.RegisterRoute("detalle", typeof(DetallePage));
        Routing.RegisterRoute("perfil", typeof(PerfilPage));
    }
}

📌 Regla clave:


5. App.xaml.cs — Configuración

En App.xaml.cs se establece AppShell como la página raíz de la aplicación. Es la única línea que cambia respecto a NavigationPage.

.NET 8 y anteriores

namespace MiApp;

public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new AppShell();
    }
}

.NET 9+ (recomendado)

namespace MiApp;

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
    }

    protected override Window CreateWindow(IActivationState activationState)
    {
        return new Window(new AppShell());
    }
}

💡 Consejo: En versiones recientes de .NET MAUI, CreateWindow es la forma recomendada. Es compatible con múltiples ventanas (Windows, Mac Catalyst) y evita el warning de MainPage obsoleta.


6. Páginas y rutas

Las páginas en Shell son ContentPage normales. La única diferencia es cómo se navega a ellas (por ruta, no por instancia).

MainPage.xaml — Página raíz

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MiApp.MainPage"
             Title="Inicio">

    <VerticalStackLayout Padding="20"
                         Spacing="20"
                         VerticalOptions="Center">

        <Label Text="🏠 Página Principal"
               FontSize="24"
               FontAttributes="Bold"
               HorizontalOptions="Center" />

        <Button Text="Ir a Detalle"
                Clicked="OnIrADetalleClicked" />

    </VerticalStackLayout>
</ContentPage>

MainPage.xaml.cs

namespace MiApp;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private async void OnIrADetalleClicked(object sender, EventArgs e)
    {
        // Navegar usando la ruta registrada
        await Shell.Current.GoToAsync("detalle");
    }
}

DetallePage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MiApp.DetallePage"
             Title="Detalle">

    <VerticalStackLayout Padding="20"
                         Spacing="20"
                         VerticalOptions="Center">

        <Label Text="📄 Página de Detalle"
               FontSize="24"
               FontAttributes="Bold"
               HorizontalOptions="Center" />

        <Button Text="← Volver"
                Clicked="OnVolverClicked" />

    </VerticalStackLayout>
</ContentPage>

DetallePage.xaml.cs

namespace MiApp;

public partial class DetallePage : ContentPage
{
    public DetallePage()
    {
        InitializeComponent();
    }

    private async void OnVolverClicked(object sender, EventArgs e)
    {
        // Volver atrás
        await Shell.Current.GoToAsync("..");
    }
}

📱 Flujo básico con Shell

Contenido textual de la representación

📱 Flujo básico con Shell

Inicio

🏠 Página Principal

  1. MainPage

→

← Detalle

📄 Página de Detalle

  1. DetallePage

7. Navegación con GoToAsync

Toda la navegación en Shell se hace con Shell.Current.GoToAsync(ruta). La ruta puede ser de varios tipos:

Ruta Efecto Equivalente en NavigationPage
"detalle" Navega a la ruta detalle (push) PushAsync(new DetallePage())
".." Vuelve a la página anterior (pop) PopAsync()
"../.." Vuelve dos páginas atrás Dos PopAsync()
"//MainPage" Va a la raíz (limpia la pila) PopToRootAsync()
"//MainPage/detalle" Va a la raíz y luego a detalle (ruta absoluta) Combinación
"detalle?productoId=5" Navega pasando parámetros Constructor parametrizado

🔀 Tipos de rutas

Contenido textual de la representación

🔀 Tipos de rutas

GoToAsync("detalle")

↓

GoToAsync("..")

↓

GoToAsync("//MainPage")

↓

GoToAsync("detalle?productoId=5")

📌 Nota sobre //: En Shell, una ruta que empieza por // es una ruta absoluta. Limpia la pila de navegación y va directamente a la página indicada. Es el equivalente a PopToRootAsync().

Ejemplo: diferentes formas de navegar

// Navegar a una página (push)
await Shell.Current.GoToAsync("detalle");

// Volver atrás
await Shell.Current.GoToAsync("..");

// Volver a la raíz
await Shell.Current.GoToAsync("//MainPage");

// Navegar pasando parámetros
await Shell.Current.GoToAsync($"detalle?productoId={producto.Id}");

// Navegar sin animación
await Shell.Current.GoToAsync("detalle", animate: false);

Puedes navegar a páginas dentro de otras páginas usando el prefijo de la ruta padre:

// Si "detalle" está registrada y tiene una subruta "editar"
await Shell.Current.GoToAsync("detalle/editar");

💡 Consejo: Registra las subrutas también en Routing.RegisterRoute. Por ejemplo:

Routing.RegisterRoute("detalle", typeof(DetallePage));
Routing.RegisterRoute("detalle/editar", typeof(EditarPage));

8. Paso de parámetros

Shell pasa parámetros por query string en la URI (?param=valor). La página destino los recibe mediante la interfaz IQueryAttributable.

Forma 1: IQueryAttributable (recomendada para valores simples)

private async void OnVerProductoClicked(object sender, EventArgs e)
{
    // Navegar pasando parámetros por query string
    await Shell.Current.GoToAsync($"detalle?productoId=42&nombre=Laptop");
}

Recibir parámetros (DetallePage.xaml.cs)

namespace MiApp;

public partial class DetallePage : ContentPage, IQueryAttributable
{
    public DetallePage()
    {
        InitializeComponent();
    }

    // Shell llama a este método automáticamente cuando navega con query params
    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        // Leer los parámetros
        string productoId = query["productoId"]?.ToString() ?? "";
        string nombre = query["nombre"]?.ToString() ?? "";

        // Actualizar la UI
        ProductoIdLabel.Text = $"ID: {productoId}";
        NombreLabel.Text = nombre;
    }
}

📌 Nota importante: Los parámetros llegan como object. Debes hacer las conversiones necesarias (ToString(), Convert.ToInt32(), etc.).

Forma 2: Pasar objetos complejos

Shell también puede pasar objetos completos (no solo strings) usando un Dictionary<string, object>.

private async void OnVerProductoClicked(object sender, EventArgs e)
{
    var producto = new Producto
    {
        Id = 42,
        Nombre = "Laptop Pro 15",
        Precio = 1299.99m
    };

    // Pasar el objeto por query
    await Shell.Current.GoToAsync("detalle", new Dictionary<string, object>
    {
        { "Producto", producto }
    });
}

Recibir el objeto (DetallePage.xaml.cs)

namespace MiApp;

public partial class DetallePage : ContentPage, IQueryAttributable
{
    private Producto _producto;

    public DetallePage()
    {
        InitializeComponent();
    }

    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        if (query.ContainsKey("Producto"))
        {
            _producto = query["Producto"] as Producto;

            if (_producto != null)
            {
                NombreLabel.Text = _producto.Nombre;
                PrecioLabel.Text = $"{_producto.Precio:C}";
            }
        }
    }
}

💡 Consejo: Para pasar objetos complejos, usa Dictionary<string, object> y accede a ellos en ApplyQueryAttributes. Los objetos se pasan por referencia, así que puedes modificarlos y ver los cambios reflejados.

Forma 3: Usar [QueryProperty] (atributo)

Otra opción es usar el atributo [QueryProperty] en la clase de la página para que Shell asigne automáticamente los parámetros a propiedades.

[QueryProperty(nameof(ProductoId), "productoId")]
[QueryProperty(nameof(Nombre), "nombre")]
public partial class DetallePage : ContentPage
{
    public string ProductoId { get; set; }
    public string Nombre { get; set; }

    public DetallePage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        // Los valores ya están asignados
        ProductoIdLabel.Text = $"ID: {ProductoId}";
        NombreLabel.Text = Nombre;
    }
}
Forma Ventaja Desventaja
IQueryAttributable Método explícito, fácil de depurar Más código
[QueryProperty] Más declarativo, menos código Requiere propiedades públicas; menos control
Dictionary<string, object> Puede pasar objetos complejos Más verboso

💡 Recomendación: Para valores simples (un id, un nombre), usa [QueryProperty]. Para objetos complejos, usa Dictionary<string, object> con IQueryAttributable.


9. Ejemplo práctico completo

Vamos a crear una app de lista de productos → detalle usando Shell. El ejemplo incluye la lista, la navegación con parámetros, y el detalle.

📱 Flujo del ejemplo con Shell

Contenido textual de la representación

📱 Flujo del ejemplo con Shell

Productos

📱 Laptop Pro

🎧 Auriculares

⌚ Smartwatch

  1. Lista

→

← Laptop Pro

📱 Laptop Pro

1.299,99€

Portátil de alto rendimiento...

  1. Detalle

Modelo — Producto

namespace MiApp;

public class Producto
{
    public int Id { get; set; }
    public string Nombre { get; set; }
    public decimal Precio { get; set; }
    public string Descripcion { get; set; }
    public string Emoji { get; set; }
}

AppShell.xaml

<?xml version="1.0" encoding="utf-8" ?>
<Shell xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:local="clr-namespace:MiApp"
       x:Class="MiApp.AppShell"
       Shell.FlyoutBehavior="Disabled"
       Title="MiApp">

    <ShellContent Title="Productos"
                  ContentTemplate="{DataTemplate local:ProductosPage}"
                  Route="ProductosPage" />

</Shell>

AppShell.xaml.cs

namespace MiApp;

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();

        // Registrar la ruta de la página de detalle
        Routing.RegisterRoute("detalle", typeof(DetalleProductoPage));
    }
}

App.xaml.cs

namespace MiApp;

public partial class App : Application
{
    public App()
    {
        InitializeComponent();
    }

    protected override Window CreateWindow(IActivationState activationState)
    {
        return new Window(new AppShell());
    }
}

ProductosPage.xaml — Lista

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MiApp.ProductosPage"
             Title="Productos">

    <CollectionView x:Name="ProductosCollectionView"
                    SelectionMode="None">

        <CollectionView.ItemTemplate>
            <DataTemplate>
                <Border Stroke="LightGray"
                        Padding="15"
                        Margin="10,5">
                    <Border.StrokeShape>
                        <RoundRectangle CornerRadius="10" />
                    </Border.StrokeShape>

                    <Grid ColumnDefinitions="Auto, *, Auto">

                        <Label Grid.Column="0"
                               Text="{Binding Emoji}"
                               FontSize="32"
                               VerticalOptions="Center"
                               Margin="0,0,15,0" />

                        <VerticalStackLayout Grid.Column="1"
                                             VerticalOptions="Center">
                            <Label Text="{Binding Nombre}"
                                   FontAttributes="Bold"
                                   FontSize="16" />
                            <Label Text="{Binding Precio, StringFormat='{0:C}'}"
                                   TextColor="#28A745"
                                   FontSize="14" />
                        </VerticalStackLayout>

                        <Button Grid.Column="2"
                                Text="Ver"
                                VerticalOptions="Center"
                                Clicked="OnVerProductoClicked" />
                    </Grid>
                </Border>
            </DataTemplate>
        </CollectionView.ItemTemplate>

    </CollectionView>
</ContentPage>

ProductosPage.xaml.cs

using System.Collections.ObjectModel;

namespace MiApp;

public partial class ProductosPage : ContentPage
{
    public ObservableCollection<Producto> Productos { get; set; }

    public ProductosPage()
    {
        InitializeComponent();

        Productos = new ObservableCollection<Producto>
        {
            new Producto
            {
                Id = 1, Emoji = "📱", Nombre = "Laptop Pro 15",
                Precio = 1299.99m,
                Descripcion = "Portátil de alto rendimiento con 16GB RAM y 512GB SSD."
            },
            new Producto
            {
                Id = 2, Emoji = "🎧", Nombre = "Auriculares Noise Cancel",
                Precio = 249.99m,
                Descripcion = "Cancelación activa de ruido y 30h de batería."
            },
            new Producto
            {
                Id = 3, Emoji = "⌚", Nombre = "Smartwatch Ultra",
                Precio = 399.99m,
                Descripcion = "Pantalla AMOLED, GPS y monitor de salud 24/7."
            }
        };

        ProductosCollectionView.ItemsSource = Productos;
    }

    private async void OnVerProductoClicked(object sender, EventArgs e)
    {
        // Obtener el producto desde el BindingContext del botón
        var boton = (Button)sender;
        var producto = boton.BindingContext as Producto;

        if (producto == null) return;

        // Navegar a detalle pasando el producto por query
        await Shell.Current.GoToAsync("detalle", new Dictionary<string, object>
        {
            { "Producto", producto }
        });
    }
}

DetalleProductoPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MiApp.DetalleProductoPage"
             Title="Detalle">

    <ScrollView>
        <VerticalStackLayout Padding="20" Spacing="20">

            <Label x:Name="EmojiLabel"
                   FontSize="80"
                   HorizontalOptions="Center" />

            <Label x:Name="NombreLabel"
                   FontSize="26"
                   FontAttributes="Bold"
                   HorizontalTextAlignment="Center" />

            <Label x:Name="PrecioLabel"
                   FontSize="22"
                   FontAttributes="Bold"
                   TextColor="#28A745"
                   HorizontalTextAlignment="Center" />

            <BoxView HeightRequest="1" Color="LightGray" />

            <Label Text="Descripción"
                   FontAttributes="Bold"
                   FontSize="16" />

            <Label x:Name="DescripcionLabel"
                   FontSize="14"
                   TextColor="Gray" />

            <Button Text="← Volver"
                    Clicked="OnVolverClicked"
                    Margin="0,20,0,0"
                    BackgroundColor="#F0F0F0"
                    TextColor="#512BD4" />

        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

DetalleProductoPage.xaml.cs

namespace MiApp;

public partial class DetalleProductoPage : ContentPage, IQueryAttributable
{
    public DetalleProductoPage()
    {
        InitializeComponent();
    }

    // Shell llama a este método cuando se navega con parámetros
    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        if (query.ContainsKey("Producto"))
        {
            var producto = query["Producto"] as Producto;

            if (producto != null)
            {
                EmojiLabel.Text = producto.Emoji;
                NombreLabel.Text = producto.Nombre;
                PrecioLabel.Text = $"{producto.Precio:C}";
                DescripcionLabel.Text = producto.Descripcion;

                // Actualizar el título de la barra
                Title = producto.Nombre;
            }
        }
    }

    private async void OnVolverClicked(object sender, EventArgs e)
    {
        // Volver atrás
        await Shell.Current.GoToAsync("..");
    }
}

💡 Observa:


10. Buenas prácticas y errores comunes

✅ Buenas prácticas:

❌ Errores comunes:

Ejemplo con accesibilidad

<Button Text="Ver detalle"
        Clicked="OnVerProductoClicked"
        SemanticProperties.Description="Ver el detalle del producto" />

Ejemplo: navegación limpia (limpiar la pila)

Cuando el usuario completa un flujo (por ejemplo, una compra), normalmente quieres limpiar la pila de navegación:

private async void OnFinalizarCompraClicked(object sender, EventArgs e)
{
    // Ir a la página de agradecimiento limpiando toda la pila
    await Shell.Current.GoToAsync("//AgradecimientoPage");
}

📌 Diferencia clave:

Ejemplo: navegación desde dentro de una página con subrutas

// En AppShell.xaml.cs
Routing.RegisterRoute("perfil", typeof(PerfilPage));
Routing.RegisterRoute("perfil/editar", typeof(EditarPerfilPage));

// Navegar a la subruta
await Shell.Current.GoToAsync("perfil/editar");

Ejemplo: pasar parámetros con [QueryProperty]

[QueryProperty(nameof(ProductoId), "productoId")]
[QueryProperty(nameof(Nombre), "nombre")]
public partial class DetallePage : ContentPage
{
    public int ProductoId { get; set; }
    public string Nombre { get; set; }

    public DetallePage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        // Los valores ya están asignados por Shell
        ProductoIdLabel.Text = $"ID: {ProductoId}";
        NombreLabel.Text = Nombre;
    }
}
// Navegar
await Shell.Current.GoToAsync($"detalle?productoId=42&nombre=Laptop");

💡 Consejo: [QueryProperty] asigna los valores después del constructor pero antes de OnAppearing. Por eso los valores están disponibles en OnAppearing, pero no en el constructor.


11. Resumen

Aspecto Detalle
Propósito Contenedor de navegación moderno que unifica tabs, flyout y jerarquía
Configuración inicial MainPage = new AppShell() o new Window(new AppShell())
Estructura visual Definida en AppShell.xaml con ShellContent, TabBar, FlyoutItem
Registro de rutas Routing.RegisterRoute("nombre", typeof(Pagina)) en AppShell.xaml.cs
Navegar (push) await Shell.Current.GoToAsync("detalle")
Volver atrás await Shell.Current.GoToAsync("..")
Volver a la raíz await Shell.Current.GoToAsync("//MainPage")
Pasar parámetros simples GoToAsync("detalle?id=5") + [QueryProperty]
Pasar objetos complejos GoToAsync("detalle", new Dictionary<string,object>{...}) + IQueryAttributable
Cuándo usar Proyectos nuevos, apps con tabs, flyout o deep linking
Alternativas NavigationPage (apps muy simples), Modal (formularios)

💡 Regla de oro: Usa Shell para cualquier proyecto nuevo en .NET MAUI. Define las páginas raíz en AppShell.xaml, registra las rutas de navegación en AppShell.xaml.cs, y navega siempre con Shell.Current.GoToAsync(ruta). Para pasar parámetros, usa [QueryProperty] (simples) o Dictionary<string, object> + IQueryAttributable (complejos). Si has entendido NavigationPage, ya tienes el 80% de Shell: solo cambia la forma de navegar (rutas en lugar de instancias).

Guía de Shell Básico en .NET MAUI


Fuente: material original · actividad del aula.