デフォルトページを指定する
特に指定しない場合,アプリケーション開始時のデフォルトのページは一番先頭に定義されたShellContent
のページになる.
アプリケーションのページの定義順とは関係なくデフォルトページを指定したい場合は以下記事のようにする.
Shell
にはCurrentItem
というプロパティがあり,ここに現在表示されているコンテンツが格納されている.
このShellの階層毎にこのCurrentItem
にコンテンツを指定していけば良い.
これはXamlではなくコードビハインドで行うので,各要素にx:Name
で名前をつけておく必要がある.
例えば,Shell -> Animals(FlyoutItem) -> Domestic(Tab) -> Dogs(ShellContent)
をデフォルトページにしたい場合は,Shellのコードビハインドで以下のようにする.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XFShellRouting.Views; namespace XFShellRouting { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MainShell : Shell { public MainShell() { InitializeComponent(); //ShellのCurrentItemを指定(shellAnimalsという名前のFlyoutItem) CurrentItem = shellAnimals; //shellAnimalsのCurrentItemを指定(shellDomesticという名前のTab) shellAnimals.CurrentItem = shellDomestic; //shellDomesticのCurrentItemを指定(shellDogsという名前のShellContent) shellDomestic.CurrentItem = shellDogs; } } }
FlyoutItem直下のShellContentをデフォルトとして指定する場合
Shell -> Animals(FlyoutItem) -> Elephants(ShellContent)
をデフォルトページに設定する場合,前述の指定方法だけではうまくいかない.
Elephantsページは表示されるが,下タブのElephants
が選択状態にならない.
この下タブまで選択状態にするためには,対象のShellContent
をShellSection
で囲み,ShellSectionにx:Name
で名前を設定してTitle
でタイトルを設定する必要がある.
<?xml version="1.0" encoding="utf-8" ?> <Shell x:Class="XFShellRouting.MainShell" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:views="clr-namespace:XFShellRouting.Views" mc:Ignorable="d"> <FlyoutItem x:Name="shellAnimals" FlyoutDisplayOptions="AsMultipleItems" Route="animals"> <Tab x:Name="shellDomestic" Title="Domestic" Route="domestic"> <ShellContent Title="Cats" ContentTemplate="{DataTemplate views:CatsPage}" Route="cats" /> <ShellContent x:Name="shellDogs" Title="Dogs" ContentTemplate="{DataTemplate views:DogsPage}" Route="dogs" /> </Tab> <ShellContent Title="Monkeys" ContentTemplate="{DataTemplate views:MonkeysPage}" Route="monkeys" /> <ShellSection x:Name="shellElephants" Title="Elephants"> <ShellContent Title="Elephants" ContentTemplate="{DataTemplate views:ElephantsPage}" Route="elephants" /> </ShellSection> <ShellContent Title="Bears" ContentTemplate="{DataTemplate views:BearsPage}" Route="bears" /> </FlyoutItem> <ShellContent Title="About" ContentTemplate="{DataTemplate views:AboutPage}" Route="about" /> </Shell>