locked
How To: Navigate between ContentPages RRS feed

  • Question

  • User80015 posted

    Coming from the Windows Phone world, I was used to navigate to any page simply with NavigationService.Navigate(new Uri("/MyOtherPage.xaml", UriKind.Relative));

    When I started to build my first serious app with Xamarin I had to realise that things aren't that simple over here. So I looked around to find a solution that comes close to the Windows Phone-Way. This is what I found out.

    If you started your first page of your app with a `ContentPage` as well, this is how you go on to navigate to your next page:

    • You can't navigate directly from a ContentPage to another.
    • A ContentPage is just content of a page container.
    • So you need a container for your ContentPages. I chose NavigationPage.

    Create a single ContentPage to your liking and make sure it descents from ContentPage

    public class WelcomePage : ContentPage
    {
       ...
    

    After declaring all your fields, fill up its constructor like this

    public WelcomePage()
    {
        //This is a setting to make my page look autonomous
        NavigationPage.SetHasNavigationBar(this, false);
    
        _loginButton.Clicked += async (s, e) =>
        {
            await Navigation.PushAsync(new LoginPage());
        };
    
        _registerButton.Clicked += async (s, e) =>
        {
            Navigation.PushAsync(new RegisterPage());
        };
    
        this.Content = new StackLayout
             {
                 Padding = new Thickness(14, 20, 14, 20),
                 Children =
                {
                    _title,
                    _descr,
                    _loginButton,
                    _registerButton,
                    _descr
                }
             };
    }
    

    Finally, all you need to do now is make your WelcomePage a child of a NavigationPage

    public class PageManager
    {
        public static NavigationPage Init()
        {
            NavigationPage nav = new NavigationPage(new WelcomePage());
            return nav;
        }
    }
    

    In your MainActivity.cs for example, boot it all up with

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
    
        Xamarin.Forms.Forms.Init(this, bundle);
        //Let's go
        SetPage(PageManager.Init());
    }
    
    Wednesday, November 26, 2014 10:23 AM

All replies

  • User1702 posted

    Navigation.PopAsync(new ContentPage());

    Replace ContentPage with the name of your class page.

    Wednesday, November 26, 2014 2:03 PM