jhen
jhen

Reputation: 1252

.NET Maui - Reset Navigation on TabBar Item Click

I currently playing around with .NET Maui and was wondering how the navigation inside the tabbar works. I could not find what I was looking for in the docs but if i missed it maybe someone can point it out for me.

So currently I have a tabbar with two bottom tabs. The second tabs show a list of items and when i click on one item i want to show a new page with details about the item selected from the list. Thats works as expected, but if I click on the first tab and then back on the second tab (the list) it does not show the list but the the detail page of the previous clicked item.

This is how my tabbar navigation is set up

<Shell
    x:Class="AthleticAlliance.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:AthleticAlliance.Views"
    Shell.FlyoutBehavior="Disabled"
    Shell.NavBarIsVisible="False">

    <TabBar>
        <Tab Title="Dashboard" Icon="home_black_24dp.svg" Route="MainPage">
            <ShellContent ContentTemplate="{DataTemplate local:MainPage}"/>
        </Tab>
        <Tab Title="Workouts" Icon="list_black_24dp.svg" Route="workouts">
            <ShellContent ContentTemplate="{DataTemplate local:WorkoutListPage}"/>
        </Tab>
    </TabBar>
</Shell>

The AppShell.xaml.cs with the routing to the details page:

public partial class AppShell : Shell
{
    public AppShell()
    {
        InitializeComponent();

        Routing.RegisterRoute(nameof(WorkoutDetailsPage), typeof(WorkoutDetailsPage));
    }
}

Is there any hint i missed in the docs or do i have to clear the navigation stack by myself in the OnDisappearing method of the details page (if that is possible, but it seems like the incorrect way and it should be more easy to do that).

Thank you in advance

// Update: Based on Jasons comment I found a way to solve my problem.

I am using the Navigation to go to the root page in the tab i am currently in via

private void ImageButton_Clicked(object sender, EventArgs e)
{
    Navigation.PopToRootAsync();
}

I don`t know why but i tried to to it in the viewModel which did not work because i do not have access to the Navigation there

Upvotes: 5

Views: 4350

Answers (1)

wonderboy
wonderboy

Reputation: 81

How about this?

protected override void OnNavigating(ShellNavigatingEventArgs args)
{
    base.OnNavigating(args);

    if (args.Source == ShellNavigationSource.ShellSectionChanged)
    {
        var navigation = Shell.Current.Navigation;
        var pages = navigation.NavigationStack;
        for (var i = pages.Count - 1; i >= 1; i--)
        {
            navigation.RemovePage(pages[i]);
        }
    }
}

Upvotes: 8

Related Questions