• Navigate Screens and Pass Data in Xamarin Forms iOS and Android Apps

    by  • May 9, 2017 • Xamarin Mobile App Development, Xamarin.Forms • 0 Comments

    In the previous post, we looked at creating a simple hello world Android and iOS app with Xamarin Forms. You now have a good understanding of how to create a new Xamarin Forms project, update Xamarin.Forms package from NuGet, and build and run the projects.

    In this post, I’m going to show you how to navigate between two screens and how to pass data between screens. The same Xamarin Forms code will work fine for Android, iOS, and UWP Apps.

    After setting up your project as shared in the previous post, you need to create a second screen or page, as it is called in Xamarin Forms, in your project. See the screenshot below on how to do that.

    01. add second page in xamarin forms application


    Once the second page is added, you need to make changes at three different places.

    1. You have to change the App.xaml.cs class
    2. You have to change the MainPage.xaml and MainPage.xaml.cs
    3. You have to change the SecondPage.xaml and SecondPage.xaml.cs

    First, let’s look at App.xaml.cs changes. In App class, you need to declare any variables which you’ll use to pass data across your screens. In our case, we have used a string variable MessageToPass. In the constructor, you have to add a new MainPage object inside a new NavigationPage object and assign it to MainPage. This will be our starting page to initialize our app with.

    Next, you need to make changes to MainPage, both in xaml and cs files. You need to add a button which when clicked will take you to the second screen. You can also add data to your shared variable i.e. MessageToPass. For the event behind the button, you need to decorate it with  async and await attributes. You also need to add the SecondPage on to the Navigation stack by pushing PushAsync method. See the code below for both xaml and cs files.

    Now, for the SecondPage, you only need to add a Label on the UI in SecondPage.xaml file and read the shared variable for the passed data and then show it on the UI as shown below.

    When you run this app on Android, iOS, or UWP, you’ll see first screen with a label and a button. Once you click the button, it will take you to the second screen and display the passed data on the label. Try it out. The sample can be downloaded from the following repository.

    Best WordPress Themes and Plugins with Great Team and Support!

    Avatar of admin


    GetCodeSnippet.com provides you high quality Microsoft .NET development related articles, tutorials and sample code for ASP.NET, C#, VB.NET, AJAX, WCF, WPF, Web Services, Windows Services, SQL Server and other technologies.

    Leave a Reply