xamarin.forms - 导航到另一个页面的命令
问题描述
执行某些操作后,我需要重定向到 ViewModel 中的另一个页面。我有按钮并设置我的命令,但是如果我第一次加载页面,那么我会收到一个错误“请使用导航页面”应用程序失败,我再次启动它并尝试加载页面并且它可以工作,但是如果我删除来自模拟器的应用程序并再次尝试我有相同的过程。
public ICommand FilterItemsCommand { get; private set; }
public FilterArticlesForPurchaseViewModel()
: base()
{
Task.Run(async () => await LoadAllDataForArticlesAndCategories()).Wait();
FilterItemsCommand = new Command(async () => await FilterItems());
}
private async Task FilterItems()
{
await Application.Current.MainPage.Navigation.PushAsync(new ArticlesForPurchaseFiltered());
}
应用程序
MainPage = new NavigationPage(GetMainPage());
我也试过这个
Application.Current.MainPage = new NavigationPage(new ArticlesForPurchaseFiltered());
但是然后我无法返回上一页,如果我使用 android 后退按钮应用程序失败顺便说一句我正在使用主详细信息
解决方案
您可以像下面的代码一样添加INavigation navigation
到 ViewModel 的构造函数中。
public ItemsViewModel(INavigation navigation)
{
Title = "Browse";
Items = new ObservableCollection<Item>();
LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
FilterItemsCommand = new Command(() => { navigation.PushModalAsync(new Page1()); });
MessagingCenter.Subscribe<NewItemPage, Item>(this, "AddItem", async (obj, item) =>
{
var newItem = item as Item;
Items.Add(newItem);
await DataStore.AddItemAsync(newItem);
});
}
当您绑定视图模型时,您可以像下面的代码一样添加属性。
public ItemsPage()
{
InitializeComponent();
BindingContext = viewModel = new ItemsViewModel(Navigation);
}
如果要在viewModel中实现导航,可以使用
// this way you need add `MainPage =new NavigationPage( new MainPage());` in app.xaml.cs
navigation.PushAsync(new Page1());
// this way you do not need `MainPage =new NavigationPage( new MainPage());` in //app.xaml.cs, just used it directly
navigation.PushModalAsync(new Page1());
推荐阅读
- excel - Powershell测试excel单元格是否为边框
- c++ - 在 C(或 C++)中分配大于 2GB 的数组
- c# - 重复 RDLC ReportViewer 子报表
- c# - How do I run .cs tests that I normally run in the Visual Studio Test Explorer, in the command line?
- oracle - 在 oracle apex 5.0 中上传文件是否有大小限制?
- java - 从 String 中获取数据并填充 RecyclerView
- aws-sam-cli - 如何从本地 AWS SAM 读取 s3 存储桶
- android - 屏幕截图大小限制改变谷歌播放
- react-native - onPress 参数不变
- uitableview - UITableViewCell 内的 UICollectionView 与 UITableViewAutoDimesion