Charles
Charles

Reputation: 417

.NET MAUI Random Shell Navigation without losing the hierarchy

This is a .NET(8) Maui app, using Shell Navigation, without Flyout or Tabs.

enter image description here

Currently I've got an individual route defined for each page in AppShell in the form of:

Routing.RegisterRoute(nameof(Mainpage), typeof(Mainpage));
Routing.RegisterRoute(nameof(A1), typeof(A1));

And I navigate down the hierarch using:

await Shell.Current.GoToAsync($"{nameof(A)}", parameters);
await Shell.Current.GoToAsync($"{nameof(A1)}", parameters);

Then navigate back up using:

await Shell.Current.GoToAsync("..");

All works fine. However I've got scenario where user needs to navigate from A1 to B1. If I use GoToAsync($"{nameof(B1)}", parameters);, navigation seems to work fine, however Navigation stack then looks like A -> A1 -> B1. Back button, using "..", naturally goes back to A1 instead of B which is unwanted.

I can navigate back from B1 using GoToAsync($"{nameof(B)}" however, this makes the stack even worse, resulting in A -> A1 -> B1 -> B. And back button ("..") goes to B1 !

I suppose one option is never using ".." and hardcode all back buttons with the name of the page one up in the hierarchy, but this is likely to result in an ever growing Navigation Stack and restricts page reuse, resulting in redundant page creations.

What would be the right navigation approach to solve this problem?

Upvotes: 0

Views: 136

Answers (2)

Charles
Charles

Reputation: 417

As far as I can see only way to navigate from A1 to B1 while maintaining navigation hierarchy is "../../B/B1". It works as intended.

This naturally creates a tight coupling, causing routing to break if another page is added. I ended up creating this method, which is not that elegant but solves my problem.

    public static async Task GoFromRootAsync(ShellNavigationState state, IDictionary<string,object> parameters = null)
    {
        var depth = Shell.Current.Navigation.NavigationStack.Count - 1;
        var backSteps = string.Concat(Enumerable.Repeat("../", depth));
        var uri = $"{backSteps}{state.Location.OriginalString}";
        await Shell.Current.GoToAsync(uri, parameters);
    }

Upvotes: 0

Stix
Stix

Reputation: 334

If you want to essentially replace the navigation stack (i.e. go straight back to B) can you use GoToAsync("//route") as from the docs this replaces the navigation stack?

Excerpt from docs:

'The route hierarchy will be searched for the specified route, upwards from the current position. The matching page will replace the navigation stack'

Upvotes: 0

Related Questions