Shell 和页面初始化

Shell and page initialization

提问人:user1803086 提问时间:11/18/2023 更新时间:11/20/2023 访问量:36

问:

我有以下xaml代码

<Shell
    x:Class="ControlBarcos.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:views="clr-namespace:ControlBarcos.Views"
    xmlns:local="clr-namespace:ControlBarcos"
    Shell.FlyoutBehavior="Flyout">
     <Shell.BackButtonBehavior>
        <BackButtonBehavior IsEnabled="True" IsVisible="True"/>
    </Shell.BackButtonBehavior>

    <Shell.ItemTemplate>
        <DataTemplate>
            <Grid ColumnDefinitions="0.2*,0.8*">
                <Image Source="{Binding Icon}"
                       Margin="5"
                       HeightRequest="25"
                       WidthRequest="25"/>
                <Label Grid.Column="1"
                       Text="{Binding Title}"
                       FontAttributes="Bold"
                       FontSize="Large"
                       VerticalTextAlignment="Center" /> 
            </Grid>
        </DataTemplate>
    </Shell.ItemTemplate>
    <ShellContent ContentTemplate="{DataTemplate views:InicialPage}" />
    <FlyoutItem Title="Barcos"
                Icon="shipdos.png">
       <Tab>
           <ShellContent ContentTemplate="{DataTemplate views:VerBarcosPage}" />
       </Tab>
    </FlyoutItem>
    <FlyoutItem Title="Empresas Externas"
                Icon="humano.png">
       <Tab>
           <ShellContent ContentTemplate="{DataTemplate views:VerEmpresasPage}" />
       </Tab>
    </FlyoutItem>
</Shell>

InicialPage是仅显示徽标的页面。 当我第一次调用“VerBarcosPage”构造函数时选择菜单选项“Barcos”,但是当再次选择该选项时,构造函数不会被调用。我需要始终调用构造函数。关于如何强制始终调用构造函数的任何想法? VerBarcosPage 的代码为:

public partial class VerBarcosPage:内容页 { 公共 VerBarcosViewModel viewModel;

public VerBarcosPage()
{
    InitializeComponent();
    viewModel = new VerBarcosViewModel();
    BindingContext = viewModel;

}

}

谢谢

C# 毛伊岛

评论


答:

0赞 Liqun Shen-MSFT #1

这是 GitHub 上的已知问题:Shell、导航和页面实例化。当您使用 shell 导航页面时,现在不会创建页面实例。

您可以尝试@PureWeen发布的解决方法。只需在 AppShell 中覆盖 OnNavigated 方法,

protected override void OnNavigated(ShellNavigatedEventArgs args)
{
    base.OnNavigated(args);
    if (CurrentItem?.CurrentItem?.CurrentItem is not null &&
        _previousShellContent is not null)
    {
        var property = typeof(ShellContent)
            .GetProperty("ContentCache", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

        property.SetValue(_previousShellContent, null);
    }

    _previousShellContent = CurrentItem?.CurrentItem?.CurrentItem;
}

我已经测试过了,页面的构造函数将再次触发。

评论

0赞 user1803086 11/20/2023
谢谢它有效......