XAML 如何通过页对象切换通过制表符?

6vl6ewon  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(138)

我正在使用MAUI编写一个应用程序,其中有一个名为Company的对象,该对象在MainPage中初始化

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

我希望该对象在两个页面之间共享,这两个页面通过运行在AppShell上的选项卡系统相互切换。

应用程序 shell .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>

我不想让对象变成static。有没有办法让对象通过两个或多个页面?我应该怎么做?

7eumitmz

7eumitmz1#

如果我有这个问题,我可能会选择这样的东西。创建类:

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

现在在MauiProgramm.cs中将其注册为单例

builder.Services.AddSingleton<CompanyContainer>();

现在,您可以通过构造函数将此示例注入到页面:

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

这应该可以解决你的问题。如果你需要的话,你也可以在MainPage中用public getter把它作为一个属性。还有一件事。在c#中,按照惯例,我们通常用大写字母写属性名。

相关问题