创建Xamarin。表单应用程序与Shell管理TabBar和汉堡菜单,我需要的菜单项做一个推作为详细页面的正确导航
我创建下一个代码:
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Pages.BasePage"
FlyoutBehavior="Flyout"
Shell.TitleColor ="Black"
Shell.TabBarBackgroundColor="#F4F4F4"
Shell.TabBarUnselectedColor="Gray"
Shell.NavBarHasShadow="True"
Shell.PresentationMode="Animated"
x:Name="shell">
<TabBar x:Name="bottomBar" Route="main">
<Tab Title="Tab 1" Icon="img1.png">
<ShellContent Route="tab-1-page" ContentTemplate="{DataTemplate views:page1}" />
</Tab>
<Tab Title="Tab 2" Icon="img2.png">
<ShellContent Route="tab-2-page" ContentTemplate="{DataTemplate views:page2}" />
</Tab>
</TabBar>
<MenuItem Text="hamburg menu item 1"
IconImageSource="menu1.png"
Command="{Binding NavigateCommand}"
CommandParameter="menu1-page" />
<MenuItem Text="hamburg menu item 2"
IconImageSource="menu2.png"
Command="{Binding NavigateCommand}"
CommandParameter="menu2-page" />
<MenuItem Text="hamburg menu item 3"
IconImageSource="menu3.png"
Command="{Binding NavigateCommand}"
CommandParameter="menu3-page" />
<Shell.FlyoutHeader>
<StackLayout BackgroundColor="white">
<Image Source="title.png" VerticalOptions="FillAndExpand" HorizontalOptions="CenterAndExpand" WidthRequest="180" />
</StackLayout>
</Shell.FlyoutHeader>
和Codebehind是:
public BasePage()
{
InitializeComponent();
BindingContext = new BaseViewModel();
}
和ViewModel是:
using HandHeldCashier.Pages;
using System;
using System.Collections.Generic;
using System.Windows.Input;
using Xamarin.Forms;
public class BaseViewModel
{
public Dictionary<string, Type> Routes { get; private set; } = new Dictionary<string, Type>();
public ICommand NavigateCommand => new Command<string>((route) => Shell.Current.GoToAsync(route));
public BaseViewModel() { }
public void RegisterRoutes()
{
Routes.Add("detail1-page", typeof(Detail1Page));
Routes.Add("detail2-page", typeof(Detail2Page));
Routes.Add("detail3-page", typeof(Detail3Page));
Routes.Add("menu1-page", typeof(AboutPage));
Routes.Add("menu2-page", typeof(CommentsPage));
Routes.Add("menu3-page", typeof(SettingsPage));
foreach (var item in Routes)
{
Routing.RegisterRoute(item.Key, item.Value);
}
}
}
这在第一次没有工作,当返回并再次访问时,它工作正常
谁知道如何替换实现或纠正这个错误?
我做了一个示例代码来检查。这对我有用。
-
确保已注册路由。在
BaseViewModel
结构中运行RegisterRoutes
方法public BaseViewModel() { RegisterRoutes(); } public void RegisterRoutes() { Routes.Add("detail1-page", typeof(Detail1Page)); Routes.Add("detail2-page", typeof(Detail2Page)); Routes.Add("detail3-page", typeof(Detail3Page)); Routes.Add("menu1-page", typeof(AboutPage)); Routes.Add("menu2-page", typeof(CommentsPage)); Routes.Add("menu3-page", typeof(SettingsPage)); foreach (var item in Routes) { Routing.RegisterRoute(item.Key, item.Value); } }
-
为了获得更好的视觉效果,您可以在操作菜单项的导航时关闭弹出框。
public ICommand NavigateCommand => new Command<string>((route) => { Shell.Current.GoToAsync(route); Shell.Current.FlyoutIsPresented = false; });