How to select specific AppShell-tab programmatically in Xamarin

410 Views Asked by At

I have been trying to navigate to the specific tab/page on a button event in the page, using the below lines, however, it doesn't work for me.

private void Button_Clicked(object sender, EventArgs e)
  {
     //Shell.Current.GoToAsync($"//MainPage/Page2", true);

     Shell.Current.GoToAsync($"//Page2", true);

  }

// My tabs in AppShell.xaml file:

 <TabBar x:Name="tb_pages"  >

        <Tab  Title="Page 1" Icon="icon_feed.png"  >
            <ShellContent  ContentTemplate="{DataTemplate local:Page1}"   />
        </Tab>

        <Tab  Title="Page 2" Icon="icon_feed.png">
            <ShellContent  ContentTemplate="{DataTemplate local:Page2}"/>
        </Tab>

<TabBar>

//AppShell.cs looks like:

 public AppShell()
   {
     InitializeComponent();
     ///

     Routing.RegisterRoute(nameof(Page1), typeof(Page1));
     Routing.RegisterRoute(nameof(Page2), typeof(Page2));

   }

I am expecting to navigate to an appropriate tab that is set in my AppShell Navigation line. I just wanna do it programmatically. I am unable to find any tab selection/click event that i could intentionally call and jump to the specific tab i want.

1

There are 1 best solutions below

6
Jessie Zhang -MSFT On

I created a demo and achieved this function, you can refer to the following code.

I added the Route for parent element TabBar and added the Route in Shell.xaml

AppShell.xaml.cs

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

    }
}

AppShell.xaml

<?xml version="1.0" encoding="UTF-8" ?> 
<Shell
    x:Class="MauiApp320.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MauiApp320"
    Shell.FlyoutBehavior="Disabled"
    
    >

    <TabBar x:Name="tb_pages" Route="root" >

        <Tab x:Name="tab1" Route="page1"  Title="Page 1" Icon="image1.png"  >
            <ShellContent  ContentTemplate="{DataTemplate local:Page1}"   />
        </Tab>

        <Tab x:Name="tab2" Route="page2" Title="Page 2" Icon="image2.png">
            <ShellContent  ContentTemplate="{DataTemplate local:Page2}"/>
        </Tab>

    </TabBar>

</Shell>

In the first page(Page1),I added a button and navigate to Page2 as follows:

public partial class Page1 : ContentPage 
{
      public Page1()
      {
            InitializeComponent();
      }

    private void Button_Clicked(object sender, EventArgs e)
    {
        Shell.Current.GoToAsync($"//page2", true);
    }
}

Note: if you want to alter to other tab at AppShell, you can refer to document Tab selection.