首页 > 解决方案 > 在 Xamarin.Forms shell 菜单中设置默认页面

问题描述

使用 Xaminals 示例,我正在尝试设置默认启动页面。这是来自xaml的相关代码:

<FlyoutItem Route="animals" x:Name="shellAnimals"
            Title="Animals"
            FlyoutDisplayOptions="AsMultipleItems">
    <Tab Title="Domestic" x:Name="shellDomestic"
         Route="domestic"
         Icon="paw.png">
        <ShellContent Route="cats" x:Name="shellCats"
                      Style="{StaticResource DomesticShell}"
                      Title="Cats"
                      Icon="cat.png"
                      ContentTemplate="{DataTemplate views:CatsPage}" />
        <ShellContent Route="dogs" x:Name="shellDogs"
                      Style="{StaticResource DomesticShell}"
                      Title="Dogs"
                      Icon="dog.png"
                      ContentTemplate="{DataTemplate views:DogsPage}" />
    </Tab>
    <ShellContent Route="monkeys" x:Name="shellMonkeys"
                  Style="{StaticResource MonkeysShell}"
                  Title="Monkeys"
                  Icon="monkey.png"
                  ContentTemplate="{DataTemplate views:MonkeysPage}" />
    <ShellContent Route="elephants" x:Name="shellElephants"
                  Style="{StaticResource ElephantsShell}"
                  Title="Elephants"
                  Icon="elephant.png"
                  ContentTemplate="{DataTemplate views:ElephantsPage}" />
    <ShellContent Route="bears" x:Name="shellBears"
                  Style="{StaticResource BearsShell}"
                  Title="Bears"
                  Icon="bear.png"
                  ContentTemplate="{DataTemplate views:BearsPage}" />
</FlyoutItem>

在后面的代码中我可以成功设置默认启动页面。

例如,狗页面:

shellAnimals.CurrentItem.CurrentItem = shellDogs;

但在熊页面上:

// This works, but I don't like the indexing. Will give trouble on dynamic menu's
shellAnimals.CurrentItem = shellAnimals.Items[3];

// This doesn't work, but I don't understand why. It gives a null reference exception in the Xamarin Shell code, on the PushAsync
shellAnimals.CurrentItem = shellBears;

// This shows the bears page at startup, but when I click on an item in the listview, I also get a null reference error
CurrentItem = shellBears;
  1. 为什么第二个/第三个片段不起作用?
  2. 如何在不使用索引器的情况下将默认页面设置为熊页面?

除了在 Xamarin Forms Shell 上设置默认选项卡之外,找不到关于此主题的任何内容,但这并没有回答。

标签: xamarin.formsxamarin.shell

解决方案


根据文档Set-the-current-flyoutitem ,您可以在 XAML 中设置当前页面。这将意味着您的Shell标签,您将添加 `CurrentItem="{x:Reference shellBears}"1。

此外,我在您的代码片段后面的第二个代码中看到,.CurrentItem与您说的狗示例相比,您缺少另一个步骤。你能试一下吗shellAnimals.CurrentItem.CurrentItem = shellBears;


推荐阅读