Home > Software design >  How to pass object through pages that swtich via Tabs?
How to pass object through pages that swtich via Tabs?

Time:12-31

I'm programming an app with MAUI where I have an object called Company that is initialized in the MainPage

public partial class MainPage : ContentPage
{
    Company company { get; set; } = new Company();

and I want that object to be shared across two pages that switch between one another through a tabs system run on the AppShell.

AppShell.xaml

<Shell
x:Class="Work_Tasks.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Work_Tasks"
xmlns:views="clr-namespace:Work_Tasks.Pages">

<TabBar>
    <ShellContent
        ContentTemplate="{DataTemplate local:MainPage}"
        Route="MainPage"
        Icon="home.png"/>
    <ShellContent
        ContentTemplate="{DataTemplate views:AddPersonel}"
        Route="AddPersonel"
        Icon="add_contact.png"/>
</TabBar>

I want to avoid making the object static. Is there any way of passing the object through both or more pages? How should I go about it?

CodePudding user response:

If I had this problem, I would probably go for something like this. Create class:

public class CompanyContainer
{
    public Company Company { get; set; } = new Company();
}

Now register it in MauiProgramm.cs as a singleton

builder.Services.AddSingleton<CompanyContainer>();

Now you can inject this instance through constructor to your page:

public partial class MainPage : ContentPage
{
    private readonly CompanyContainer _companyContainer;
    
    public MainPage(CompanyContainer container)
    {
        _companyContainer = container;
    }
}

This should solve your issue. You can also make it as a property with public getter in MainPage if you need. And one more thing. In c# by convention we usually write property names with capital letter.

  • Related