正如你在这里看到的MvvmCross 游乐场 https://github.com/MvvmCross/MvvmCross/tree/develop/Projects/Playground,您应该首先创建一个 RootViewModel、MenuViewModel 和 FirstViewModel。然后在 UI 文件夹中创建 RootPage、MenuPage 和 FirstPage。
您的 RootViewModel 应如下所示:
public class RootViewModel : BaseViewModel
{
private readonly IMvxNavigationService _navigationService;
public RootViewModel(IMvxNavigationService navigationService)
{
_navigationService = navigationService;
}
public override void ViewAppearing()
{
base.ViewAppearing();
MvxNotifyTask.Create(async ()=> await this.InitializeViewModels();
}
private async Task InitializeViewModels()
{
await _navigationService.Navigate<MenuViewModel>();
await _navigationService.Navigate<FirstViewModel>();
}
}
edit:我将导航移至异步任务以避免使用 async void。
xaml RootPage 必须实现 MvxMasterDetailPage:
<?xml version="1.0" encoding="UTF-8"?>
<views:MvxMasterDetailPage x:TypeArguments="viewModels:RootViewModel"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
xmlns:mvx="clr-namespace:MvvmCross.Forms.Bindings;assembly=MvvmCross.Forms"
xmlns:viewModels="clr-namespace:yournamespace.Core.ViewModels"
x:Class="yournamespace.UI.Views.RootPage"
Icon="hamburger.png">
</views:MvxMasterDetailPage>
后面的 C# 代码使用 Presenter,如下所示:
[MvxMasterDetailPagePresentation(MasterDetailPosition.Root, WrapInNavigationPage = false)]
public partial class RootPage : MvxMasterDetailPage<RootViewModel>
{
public RootPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
}
}
MenuPage 必须是普通的 MvxContentPage 和 C# 代码,在菜单页面上实现演示者:
[MvxMasterDetailPagePresentation(MasterDetailPosition.Master)]
FirstPage 也是 MvxContentPage 并且所有详细信息页面必须是:
[MvxMasterDetailPagePresentation(MasterDetailPosition.Detail, NoHistory = true)]
在主详细信息的所有页面中添加无历史记录,以防止导航返回错误。
edit:我忘记了,有一个错误导致菜单在导航后无法关闭,可能他们会在 MvvmCross 版本 6 上修复,要修复它,您必须在执行导航之前将其粘贴到导航任务中:
if(Application.Current.MainPage is MasterDetailPage masterDetailPage)
{
masterDetailPage.IsPresented = false;
}
else if(Application.Current.MainPage is NavigationPage navigationPage && navigationPage.CurrentPage is MasterDetailPage nestedMasterDetail)
{
nestedMasterDetail.IsPresented = false;
}