我是MAUI的新手,我正在尝试将登录页面中收集的数据传递到选项卡页面。我试图通过使用shell导航方法的数据,但它似乎没有在我的任何选项卡页面上可用。
导航代码:
await Shell.Current.GoToAsync($"//PortalTabs", true, new Dictionary<string, object>
{
//Data that must be passed to App page
{"User", user}
});
使用Maui Community工具包,在第一个选项卡(AppViewModel):
//Data brought forward from previous page
[QueryProperty(nameof(User), "User")]
public partial class AppViewModel : ViewModelBase
{
//Observable Properties
[ObservableProperty]
UserModel user;
public AppViewModel()
{
}
}
AppShell.xaml:
<!--Portal Tabs-->
<TabBar Route="PortalTabs">
<Tab Title="Apps">
<ShellContent ContentTemplate="{DataTemplate views:AppPage}"/>
</Tab>
<Tab Title="Profile">
<ShellContent ContentTemplate="{DataTemplate views:ProfilePage}"/>
</Tab>
<Tab Title="Settings">
<ShellContent ContentTemplate="{DataTemplate views:SettingsPage}"/>
</Tab>
</TabBar>
我正在尝试使用AppPage上的数据通过:
<Label Text = "{Binding User.Username}"
我错过了什么明显的吗?
我发现了这个问题。路由必须是到需要数据的页面,而不是路由到标签栏。作为对Isidoros的回答的回应:我的页面确实通过ViewModelBase继承了ObservableObject,并且我的绑定上下文已经设置在页面后面的代码上了。
工作导航:
await Shell.Current.GoToAsync($"//AppPage", true, new Dictionary<string, object>
{
//Data that must be passed to App page
{"User", user}
});
添加到AppShell.xaml:
的路由<!--Portal Tabs-->
<TabBar Route="PortalTabs">
<Tab Title="Apps" Route="AppPage">
<ShellContent ContentTemplate="{DataTemplate views:AppPage}"/>
</Tab>
<Tab Title="Profile">
<ShellContent ContentTemplate="{DataTemplate views:ProfilePage}"/>
</Tab>
<Tab Title="Settings">
<ShellContent ContentTemplate="{DataTemplate views:SettingsPage}"/>
</Tab>
</TabBar>
命令Shell.Current.GoToAsync将参数传递给页面而不是底层视图模型。把你的代码移到后面的页面代码
//Data brought forward from previous page
[QueryProperty(nameof(User), "User")]
public partial class AppPage : ContentPage
{
User user;
public User User
{
set
{
user = value;
BindingContext = new AppViewModel(user);
}
}
public AppPage()
{
InitializeComponent();
//no binding here. Set the binding when you receive
//the data from the property.
}
....
}
你的视图模型应该看起来像下面(注意参数userparam和ObservableObject继承类是MVVM工作所必需的):
public partial class AppViewModel : ObservableObject
{
//Observable Properties
[ObservableProperty]
User user;
public AppViewModel(User userparam)
{
user = userparam;
}
}