B. Hulshof B. Hulshof - 23 days ago 17
Android Question

Xamarin - TabbedPage navigation error (page must not have a parrent)

So I'm getting the Page must not already have a parent exception. This happens when I try to navigate from a page to another page which is already contained within another tab. Before I load my pages in the TabbedPage itself I put them in one list called pages, this is obviously where the TabbedPage is getting its children from. I`m also trying to get this list to work with my navigation buttons. But whenever I try to use them I get the exception. Here is how I load the pages:

private int pageNavCount = 0;
private list<ContentPage> pages = nwe List<ContentPage> (0);

public MainCPage ()
{
Create ();

Children.Add(pages[0]);
Children.Add(pages[1]);
Children.Add(pages[2]);
}


and here is how I put a page into the list:

pages.Add (new ContentPage {
Title="Start Pagina",
BackgroundImage="@drawable/background.jpg",
Content = new StackLayout {
Padding = 50,
BackgroundColor = Color.Black,
Opacity = 0.75,
Children = {
//The controls and stuff
}
}
});


And this is how I'm using the page list with my navigation buttons:

private void NavButtonNext_Clicked (object sender, EventArgs e)
{
pageNavCount++;
this.Navigation.PushAsync(pages[pageNavCount]);
}

private void NavButtonPrev_Clicked (object sender, EventArgs e)
{
pageNavCount--;
this.Navigation.PushAsync(ages[pageNavCount]);
}


When I try to push a button I get the "Page must not already have a parent" exception.
And I don't want to end up making new buttons for every single page! Can someone please tell me what I`m doing wrong here?

Answer

If you want to navigate to a page in another tab that is already open, then you should do something like this:

// you will need a reference to your TabbedPage
pageNavCount--;
tabs.CurrentPage = pages[pageNavCount];

This blog has a good writeup on programmatically switching tabs.

Comments