Search code examples
c#.netmaui.net-maui

How to pass data when navigating through TabBar?


To pass data beetwen viewmodels when navigating I use query parameters (IQueryAttributable), i.e.:

NavigationParameters[nameof(SomeProperty)] = SomeProperty;
await Shell.Current.GoToAsync("SomePage", NavigationParameters);

It works as it should be working, but I wish to put SomePage into a TabBar:

<TabBar>
    <ShellContent Route="SomePage"
        ContentTemplate="{DataTemplate local:SomePage}"/>
    ...
</TabBar>

Is there a way to pass data when user click/tap SomePage icon on the tab bar? Is there some event for that so I could hook up GoToAsync method? Or maybe there is another way than query to pass data beetwen viewmodels?


Solution

  • MauiProgram.cs:

    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder.UseMauiApp<App>();
            builder.Services
                .AddSingleton<Page_1>
                .AddSingleton<ViewModel_1>
                .AddSingleton<Page_2>
                .AddSingleton<ViewModel_2>
                .AddSingleton<ISharedDataInterface, SharedDataInterfaceImplementation>();
            return builder.Build();
        }
    }
    

    Page_1.xaml.cs:

    public partial class Page_1 : ContentPage
    {
        public LogoPage(ViewModel_1 viewModel_1)
        {
            BindingContext = viewModel_1;
    
            InitializeComponent();
        }
    }
    

    Page_2.xaml.cs:

    public partial class Page_2 : ContentPage
    {
        public LogoPage(ViewModel_2 viewModel_2)
        {
            BindingContext = viewModel_2;
    
            InitializeComponent();
        }
    }
    

    ViewModel_1.cs:

    public class ViewModel_1
    {
        public ViewModel_1(ISharedDataInterface sharedDataInterfaceImplementation)
        {
            ...
        }
    }
    

    ViewModel_2.cs:

    public class ViewModel_2
    {
        public ViewModel_2(ISharedDataInterface sharedDataInterfaceImplementation)
        {
            ...
        }
    }