首页 > 解决方案 > 导航到另一个页面的命令

问题描述

执行某些操作后,我需要重定向到 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 后退按钮应用程序失败顺便说一句我正在使用主详细信息

标签: xamarin.forms

解决方案


您可以像下面的代码一样添加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());

推荐阅读