Xamarin可移植项目使用MasterDetailPage将ToolbarItem导航到另一个页面

时间:2016-05-16 13:28:20

标签: c# xamarin

我正在创建迷你应用程序,我想从我的工具箱标签导航到另一个页面。 我的App.cs:

public class App : Application
    {
        public App()
        {
            MainPage = new MainPage();
        }
        protected override void OnStart()
        {}
    }

这是继承自MasterDetailPage的主页:

public partial class MainPage : MasterDetailPage
{
    public MainPage()
    {
        InitializeComponent();
        masterPage.ListView.ItemSelected += OnItemSelected;

        if (Device.OS == TargetPlatform.Windows)
        {
            Master.Icon = "swap.png";
        }

        CityClick.Clicked += async (sender, e) =>
        {
            await Navigation.PushAsync(new Cities());
        };
    }
    void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var item = e.SelectedItem as MasterPageItem;
        if(item != null)
        {
            Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
            masterPage.ListView.SelectedItem = null;
            IsPresented = false;
        }
    }

这是MainPage XAML结构:

<?xml version="1.0" encoding="UTF-8"?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
                  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                  xmlns:local="clr-namespace:DD.Learning;assembly=DD.Learning"
                  x:Class="DD.Learning.MainPage"
          MasterBehavior="Popover">
  <ContentPage.ToolbarItems>
    <ToolbarItem x:Name="CityClick"
                 Text="City :"
                 Order="Primary">
    </ToolbarItem>
  </ContentPage.ToolbarItems>

  <MasterDetailPage.Master>
    <local:MasterPage x:Name="masterPage" />
  </MasterDetailPage.Master>
  <MasterDetailPage.Detail>
    <NavigationPage>
      <x:Arguments>
        <local:UnpaidVehicle />
      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>

当我尝试在MainPage中执行CityClick.Clicked += asyn .... await Navigation...(new Cities());时。它抛出错误:System.InvalidOperationException: PushAsync is not supported globally on Android, please use a NavigationPage.,因为我在MasterDetailPage中执行此操作,并且该操作仅在MainPage继承ContentPage类时才可用。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

我通过从await Navigation.PushAsync(new (new Cities());更改为此await Navigation.PushModalAsync(new Cities());来解决此问题。所以我仍然不理解PushAsyncPushModalAsync之间的差异。在该实现之后,我的城市页面也会出现,但导航栏会消失。有人知道我的导航栏消失的原因吗?

答案 1 :(得分:0)

PushModalAsync在当前页面上创建一个弹出窗口类型的页面。而PushAsync替换当前页面。

您可以浏览以下链接: https://jfarrell.net/2015/01/22/understanding-xamarin-forms-navigation/

从以下评论中更新解决方案是:

await this.Detail.Navigation.PushAsync(new Cities());