我正在尝试使用MvvmCross为我的导航实现TabbedPage。问题是MvvmCross使用ViewModel第一个导航,这似乎不能很好地用于将子项添加到TabbedPage的一般方法;因为我在页面构建期间无法访问非null的ViewModel,但我可以在OnBindingContextChanged
内访问它。
这是我到目前为止所拥有的......
DashboardPage.xaml:
<?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DashboardPage"
xmlns:local="clr-namespace:CoreUI;assembly=CoreUI"
SelectedItem="{Binding CurrentSection, Mode=TwoWay}">
</TabbedPage>
DashboardPage.xaml.cs:
public partial class DashboardPage : TabbedPage
{
public DashboardPage()
{
InitializeComponent();
}
protected override void OnBindingContextChanged()
{
var vm = (BindingContext as DashboardViewModel);
if (vm == null)
{
return;
}
ObservableCollection<MainMenuSection> sections = vm.MenuSections;
foreach (var section in sections)
{
MainMenuViewModel main_menu_vm = new MainMenuViewModel
{
Section = section
};
// Question 2:
// Going against the MvvmCross grain here by referring to other pages from within a page, as opposed to doing everything from a ViewModel. How do I get around this?
Children.Add(new MainMenuPage(main_menu_vm));
}
}
}
MainMenuPage.xaml(注意此处的评论):
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MainMenuPage"
xmlns:local="clr-namespace:CoreUI;assembly=CoreUI"
Title="{Binding Title}" > <!-- The tabs that are displayed on Dashboard have the correct labels, so Binding appears to be working here. -->
<ContentPage.Content>
<StackLayout x:Name="Body" IsVisible="false">
<Label Text="{Binding Title}"/> <!-- Label doesn't get displayed, but does get displayed if Text is bound to something static, so Binding not quite working here. -->
</StackLayout>
</ContentPage.Content>
</ContentPage>
MainMenuPage.xaml.cs:
public partial class MainMenuPage : ContentPage
{
public MainMenuPage(MainMenuViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
protected override void OnBindingContextChanged()
{
Body.IsVisible = true;
}
}
上面的MainMenuPage是我要说明的观点的简化版本,即DashboardPage中的每个标签都有一个空白页面。
问题1 :为什么标签页空白?
问题2 :请参阅DashboardPage.xaml.cs中的评论。
答案 0 :(得分:0)
你为什么要自己做这整件事?正如您在样本(https://github.com/MvvmCross/MvvmCross/tree/develop/TestProjects/Playground/Playground.Forms.UI/Pages)中看到的那样,您可以使用MvxTabbePagePresentation
属性装饰您的视图,MvvmCross将为您处理其余的视图!
我还建议使用Mvx
类型页面来利用许多功能。