Buscar..


Flujo de navegación

using System;
using Xamarin.Forms;

namespace NavigationApp
{    
    public class App : Application
    {
        public App()
        {
            MainPage = new NavigationPage(new FirstPage());
        }
    }

    public class FirstPage : ContentPage
    {
        Label FirstPageLabel { get; set; } = new Label();

        Button FirstPageButton { get; set; } = new Button();

        public FirstPage()
        {
            Title = "First page";

            FirstPageLabel.Text = "This is the first page";
            FirstPageButton.Text = "Navigate to the second page";
            FirstPageButton.Clicked += OnFirstPageButtonClicked;

            var content = new StackLayout();
            content.Children.Add(FirstPageLabel);
            content.Children.Add(FirstPageButton);

            Content = content;
        }

        async void OnFirstPageButtonClicked(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new SecondPage(), true);
        }
    }

    public class SecondPage : ContentPage
    {
        Label SecondPageLabel { get; set; } = new Label();

        public SecondPage()
        {
            Title = "Second page";

            SecondPageLabel.Text = "This is the second page";

            Content = SecondPageLabel;
        }
    }
}    

Archivo App.xaml.cs (el archivo App.xaml es predeterminado, así que se omite)

using Xamrin.Forms

namespace NavigationApp
{
    public partial class App : Application
    {
        public static INavigation GlobalNavigation { get; private set; }

        public App()
        {
            InitializeComponent();
            var rootPage = new NavigationPage(new FirstPage());

            GlobalNavigation = rootPage.Navigation;

            MainPage = rootPage;
        }
    }
}

Archivo FirstPage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="NavigationApp.FirstPage"
    Title="First page">
    <ContentPage.Content>
        <StackLayout>
            <Label
                Text="This is the first page" />
            <Button
                Text="Click to navigate to a new page" 
                Clicked="GoToSecondPageButtonClicked"/>
            <Button
                Text="Click to open the new page as modal" 
                Clicked="OpenGlobalModalPageButtonClicked"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

En algunos casos, necesita abrir la nueva página no en la navegación actual sino en la global. Por ejemplo, si su página actual contiene el menú inferior, será visible cuando presione la nueva página en la navegación actual. Si necesita que la página se abra sobre todo el contenido visible que oculta el menú inferior y el contenido de otra página actual, debe insertar la nueva página como modal en la navegación global. Consulte la propiedad App.GlobalNavigation y el ejemplo a continuación.

Archivo FirstPage.xaml.cs

using System;
using Xamarin.Forms;

namespace NavigationApp
{
    public partial class FirstPage : ContentPage
    {
        public FirstPage()
        {
            InitializeComponent();
        }

        async void GoToSecondPageButtonClicked(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new SecondPage(), true);
        }

        async void OpenGlobalModalPageButtonClicked(object sender, EventArgs e)
        {
            await App.GlobalNavigation.PushModalAsync(new SecondPage(), true);
        }
    }
}

Archivo SecondPage.xaml (el archivo xaml.cs es predeterminado, por lo que se omite)

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="NavigationApp.SecondPage"
    Title="Second page">
    <ContentPage.Content>
        <Label
            Text="This is the second page" />
    </ContentPage.Content>
</ContentPage>

De forma predeterminada, el patrón de navegación funciona como una pila de páginas, y llama a las páginas más recientes sobre las páginas anteriores. Necesitará usar el objeto NavigationPage para esto.

Empujando nuevas páginas

...
public class App : Application 
{
    public App() 
    {
        MainPage = new NavigationPage(new Page1());
    }
}
...

Page1.xaml

...
<ContentPage.Content>
    <StackLayout>
        <Label Text="Page 1" />
        <Button Text="Go to page 2" Clicked="GoToNextPage" />
    </StackLayout>
</ContentPage.Content>
...

Page1.xaml.cs

...
public partial class Page1 : ContentPage
{
    public Page1()
    {
        InitializeComponent();
    }
    
    protected async void GoToNextPage(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new Page2());
    }
}
...

Page2.xaml

...
<ContentPage.Content>
    <StackLayout>
        <Label Text="Page 2" />
        <Button Text="Go to Page 3" Clicked="GoToNextPage" />
    </StackLayout>
</ContentPage.Content>
...

Page2.xaml.cs

...
public partial class Page2 : ContentPage
{
    public Page2()
    {
        InitializeComponent();
    }
    
    protected async void GoToNextPage(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new Page3());
    }
}
...

Saltando páginas

Normalmente, el usuario usa el botón Atrás para regresar páginas, pero a veces necesita controlar esto programáticamente, por lo que debe llamar al método NavigationPage.PopAsync () para regresar a la página anterior o NavigationPage.PopToRootAsync () para regresar al principio, tales como ...

Page3.xaml

...
<ContentPage.Content>
    <StackLayout>
        <Label Text="Page 3" />
        <Button Text="Go to previous page" Clicked="GoToPreviousPage" />
        <Button Text="Go to beginning" Clicked="GoToStartPage" />
    </StackLayout>
</ContentPage.Content>
...

Page3.xaml.cs

...
public partial class Page3 : ContentPage
{
    public Page3()
    {
        InitializeComponent();
    }
    
    protected async void GoToPreviousPage(object sender, EventArgs e)
    {
        await Navigation.PopAsync();
    }

    protected async void GoToStartPage(object sender, EventArgs e)
    {
        await Navigation.PopToRootAsync();
    }
}
...

Las páginas modales se pueden crear de tres maneras:

  • Desde el objeto NavigationPage para páginas de pantalla completa
  • Para Alertas y Notificaciones
  • Para ActionSheets que son menús emergentes.

Modales de pantalla completa

...
// to open
await Navigation.PushModalAsync(new ModalPage());
// to close
await Navigation.PopModalAsync();
...

Alertas / Confirmaciones y Notificaciones

...
// alert
await DisplayAlert("Alert title", "Alert text", "Ok button text");
// confirmation
var booleanAnswer = await DisplayAlert("Confirm?", "Confirmation text", "Yes", "No");
...

Hojas de acción

...
var selectedOption = await DisplayActionSheet("Options", "Cancel", "Destroy", "Option 1", "Option 2", "Option 3");
...

Página raíz de detalles maestros

public class App : Application
{
    internal static NavigationPage NavPage;

    public App ()
    {
        // The root page of your application
        MainPage = new RootPage();
    }
}
public class RootPage : MasterDetailPage
{
    public RootPage()
    {
        var menuPage = new MenuPage();
        menuPage.Menu.ItemSelected += (sender, e) => NavigateTo(e.SelectedItem as MenuItem);
        Master = menuPage;
        App.NavPage = new NavigationPage(new HomePage());
        Detail = App.NavPage;
    }
    protected override async void OnAppearing()
    {
        base.OnAppearing();
    }
    void NavigateTo(MenuItem menuItem)
    {
        Page displayPage = (Page)Activator.CreateInstance(menuItem.TargetType);
        Detail = new NavigationPage(displayPage);
        IsPresented = false;
    }
}

Detalle maestro de navegación

El siguiente código muestra cómo realizar una navegación asíncrona cuando la aplicación se encuentra en un contexto MasterDetailPage.

public async Task NavigateMasterDetail(Page page)
{
        if (page == null)
            {
                return;
            }

        var masterDetail = App.Current.MainPage as MasterDetailPage;

        if (masterDetail == null || masterDetail.Detail == null)
            return;         

        var navigationPage = masterDetail.Detail as NavigationPage;
        if (navigationPage == null)
        {
            masterDetail.Detail = new NavigationPage(page);
            masterDetail.IsPresented = false;
            return;
        }

        await navigationPage.Navigation.PushAsync(page);

        navigationPage.Navigation.RemovePage(navigationPage.Navigation.NavigationStack[navigationPage.Navigation.NavigationStack.Count - 2]);
        masterDetail.IsPresented = false;
    }


Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow