I've been trying to make it so that I can change the root page of my application, specifically so that I can show an ActivityIndicator until the app is ready to start, and then navigate to either a Sign In Page or the Main Page of the application. Browsing the forums, I saw the main suggestion was to display the Sign In Page as a modal popup, or to swap the Contents of the root page. I never got the Content swapping to work properly, and the modal popup just doesn't sit right with me, so I came up with this:
public class SwappableRootNavigationPage : NavigationPage
{
private class RootPage : MultiPage<Page>
{
protected override Page CreateDefault(object item)
{
//Not needed for this use of a MultiPage (At least not that I've seen...)
throw new NotImplementedException();
}
}
private RootPage _root;
public SwappableRootNavigationPage() : base (new RootPage())
{
_root = CurrentPage as RootPage;
//Create the default "Splash" page
_root.Children.Add(new ContentPage()
{
Content = new ActivityIndicator()
{
IsRunning = true,
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
}
});
}
public async Task SwapRoot<T>() where T : Page, new()
{
await PopToRootAsync();
//Use the MultiPage to display a new page, removing the old to prevent overlapping of views
_root.Children.RemoveAt(0);
_root.Children.Add(new T());
//TODO Add an animation here to make it look like a normal entrance?
}
}
It takes the place of the NavigationPage passed from GetMainPage() and takes advantage of the MultiPage's ability to display full Pages without messing with Parents, INavigation, etc. (Which seems to be why Content swapping wasn't working).
The RootPage class is private because I didn't want anything outside of this class to modify _root's children, which may have caused problems with overlapping views. At least that's what happened when I tried to use the MultiPage originally and allowed for multiple children.
This works perfectly for what I needed/wanted, with the exception that the SwapRoot does not animate the new Page. If anyone has any suggestions on how to do that, I'd be grateful!