如何删除或隐藏特定页面错误中的工具栏项:System.IndexOutOfRangeException:索引超出了数组的范围

Bin*_*Tie 15 c# xamarin.ios toolbaritems xamarin xamarin.forms

我想Remove()Clear() ToolbarItems.这是我ToolbarItem在MainPage.cs中创建的代码

public partial class MainPage : MasterDetailPage
{
   public ToolbarItem cCounter = new ToolbarItem() { Icon = "picture.png" };
   public ToolbarItem pPo = new ToolbarItem() { Text = "-" };

   public MainPage()
    {
        InitializeComponent();
        if (Device.OS == TargetPlatform.iOS)
        {
            provider.Clicked += iOS_Ppo_Clicked;
            ToolbarItems.Add(cCounter);
            ToolbarItems.Add(pPo);
        }
    }

    private void iOS_Ppo_Clicked(object sender, EventArgs e)
    { 
        OpenWindow();            
    }

    public async void OpenWindow()
    {
        if (await Common.WindowComands.CanOpenWindow<PPoPage>(Detail))
        {  
            page = new PPoPage(Page3.Allproviders);

            this.ToolbarItems.Clear(); // here I am getting error:Index was outside the bounds of the array 

            page.OnSelected += Page_OnSelected;
            await Detail.Navigation.PushAsync(page, false);             
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:当我this.ToolbarItems.Clear();OpenWindow 方法中包含初始化另一个页面打开并且它有效!清除所有工具栏项,但不幸的是显示此错误:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
Run Code Online (Sandbox Code Playgroud)

如您所见,此项目应仅在iOS中消失.这是我的页面类,我想Remove()这些ToolbarItems:

public partial class PPoPage : ContentPage
{
   public MainPage main { get; set; }

   private List<PPo> Pro;

   public PPoPage(List<PPo> po)
   {
      InitializeComponent();
      if (Device.OS == TargetPlatform.iOS)
      {
         Pro = po;
         CreateLayout();
         // HERE I WANT TO REMOVE TOOLBARITEMS FOR THIS PAGE
         this.ToolbarItem.Remove(main.cCounter); // here there is error
         this.ToolbarItems.Clear(); // this also doesn't work, because toolbar items still exist after this initialization.
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

在这堂课中,我尝试了两种方法,但都没有效果.感谢您的回答或建议.

Bin*_*Tie 1

首先,我真的要感谢所有答案和建议,我尝试在我的解决方案中实现这两个答案,但不幸的是没有成功。主要原因是我没有专注于在我的 iOS 项目中实现整个 iOS 工具栏的类。

在iOS工具栏上我只写了简单的if语句:

var currentPage = ((NavigationPage)Element).CurrentPage;
if (currentPage != null && currentPage is ContentPage)
{
    TopViewController.NavigationItem.RightBarButtonItems = new UIBarButtonItem[0];
                return;
}
Run Code Online (Sandbox Code Playgroud)