Hello,
want to achieve the same functionality in .NET MAUI, where selecting a tab will navigate to the root of the navigation stack
You can do this by adding the shell custom code in the Platform/Android folder, remove [assembly: ExportRenderer(typeof(CustomShell), typeof(CustomShellRenderer))]
and change Xamarin.Forms.Device.BeginInvokeOnMainThread
to MainThread.InvokeOnMainThreadAsync
like following code.
namespace Dev.Platforms.Android
{
public class CustomShellRenderer : ShellRenderer
{
/// <summary>
/// CustomShellRenderer
/// </summary>
/// <param name="context"></param>
public CustomShellRenderer(Context context) : base(context)
{
}
/// <summary>
/// IShellItemRenderer
/// </summary>
/// <param name="shellItem"></param>
/// <returns></returns>
protected override IShellItemRenderer CreateShellItemRenderer(ShellItem shellItem)
{
return new CustomShellItemRenderer(this);
}
}
/// <summary>
/// CustomShellItemRenderer
/// </summary>
public class CustomShellItemRenderer : ShellItemRenderer
{
/// <summary>
/// TodoShellItemRenderer
/// </summary>
/// <param name="shellContext"></param>
public CustomShellItemRenderer(IShellContext shellContext) : base(shellContext)
{
}
/// <summary>
/// Pops to root when the selected tab is pressed.
/// </summary>
/// <param name="shellSection"></param>
protected override void OnTabReselected(ShellSection shellSection)
{
base.OnTabReselected(shellSection);
try
{
MainThread.InvokeOnMainThreadAsync(async () => {
await shellSection?.Navigation.PopToRootAsync();
});
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
Then register this custom renderer in the MauiProgram.cs
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
...
//register it at here
builder.ConfigureMauiHandlers(handlers =>
{
#if ANDROID
handlers.AddHandler<AppShell, Dev.Platforms.Android.CustomShellRenderer>();
#endif
});
}
}
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.