【发布时间】:2018-05-10 07:13:55
【问题描述】:
我正在尝试使用 MvvmCross 实现 TabbedPage 进行导航。问题是 MvvmCross 使用 ViewModel 第一个导航,这似乎与将子项添加到 TabbedPage 的一般方法不兼容;因为在页面构建期间我无法访问非空 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(注意这里的cmets):
<?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 中的每个选项卡获得一个空白页。
问题一:为什么标签页是空白的?
问题 2:参考 DashboardPage.xaml.cs 中的注释。
【问题讨论】:
标签: xaml xamarin.forms mvvmcross