Xamarin相对较新,遇到了PushAsync和我无法弄清楚的导航问题。
我有一个主导航页面,然后有一个“ MyContentPage”,它负责根据提供的ID呈现动态列表。当用户单击列表项时,他们将转到具有不同ID的下一个(已更新)“ MyContentPage”(同一类)。基本上是基于本地数据库的递归页面层次结构。
问题是导航似乎以某种我无法解决的方式很快搞砸了。页面被交换或丢失。导航回到根目录,如果我再次单击向下,它会跳到下一页等。
因此,基本上,与首页分开的页面(选项卡中有多个导航页-尽管此时我仅使用一个选项卡)将其控件绑定到此功能:
public async Task NavigateToContent(int contentId)
{
await ((Application.Current.MainPage) as TabbedPage)?.CurrentPage.Navigation.PushAsync(new MyContentPage(contentId));
}
然后将以上内容递归使用。就是相似的控件将绑定到同一功能,直到没有其他页面可以单击为止。
MyContentPage构造函数加载模型:
public MyContentPage(int id)
{
InitializeComponent();
_id = id;
BindingContext = viewModel = new ContentPageViewModel(id);
}
这是什么问题?
答案 0 :(得分:0)
From what you mentioned in comments, the issue is caused by the navigation code called in the 'service' class. When you call the service method multiple times, it actually changes the current navigation stack in xamarin forms. Move the page navigation code from service class to viewmodel class.
Or try to put the page navigation source code into something like 'NavigationService' (one example is the one in https://docs.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/ ) and inject this service into your view model class.
答案 1 :(得分:0)
好,所以所有这些都与并发有关。
原始按钮单击是这样的:
private void Button_Clicked(object sender, EventArgs e)
{
Task.Run(async () => await (BindingContext as ContentPageViewModel).ExecuteNavCommand(sender));
}
但这会导致在其他任务上发生UI操作
事件处理程序可以声明为异步
更正为
private async void Button_Clicked(object sender, EventArgs e)
{
await viewModel.ExecuteNavCommand(sender);
}