0
votes

I am developing Xamarin Forms application for IOS and Android.I have the list of 3 xamarin form pages say X.xaml, Y.xaml, Z.xaml. Page X.xaml, Y.xaml is having 1 and click on that button it opens the next-next Xamarin form. And last on Z.xaml having 2 buttons btnBack & btnConfirm

<Button x:Name="btnBack"></Button>
<Button x:Name="btnConfirm"></Button>

when I click on that back button I want to navigate it to my previous page, but I don't want it like Navigation Back Button or Hardware Back Button click. for this I have tried this code this will not work.

Z.xaml.cs

public partial class Z : ContentPage
        {
            public Z()
            {
                InitializeComponent();                   
                btnBack.Clicked += btnBack_Clicked;
            }   
            private void btnBack_Clicked(object sender, EventArgs e)
            {
                var existingPages = Navigation.NavigationStack.ToList();
                foreach (var page in existingPages)
                {
                    if(page == this)
                        Navigation.RemovePage(page);
                }
            }
        }   

In this code when I click on Back Button it Navigate me to prevoius page ie Y.xaml once I click on button which is on Y.xaml and open the Z.xaml page it shows me blank.

Y.xaml.cs

 public partial class Y: ContentPage
      {
        public Y()
         {
            InitializeComponent();
            btnZ.Clicked += btnZ_Clicked;
          } 
         void btnZ_Clicked(object sender, System.EventArgs e)
           {            
              Navigation.PushAsync(new Z());
            }
       }
2

2 Answers

1
votes

@Kowalski had the right answer however it is incomplete.

You have to await Navigation.PopAsync() otherwise you may mess up the navigation stack. So always await it. Example:

async void btnBack_Clicked(object sender, EventArgs e)
{
    await Navigation.PopAsync();
}

Beside that be aware that there are bugs in Xamarin.Forms related to navigation, here is one that might be interesting for you as well: https://bugzilla.xamarin.com/show_bug.cgi?id=59172

P.S.: Here you can find the official guide on Popping Pages from the Navigation Stack.

0
votes

you should invoke Navigation.PopAsync() to go back