BinaryTie BinaryTie - 2 months ago 10
C# Question

How to remove or hide Toolbar item in specific page error: System.IndexOutOfRangeException: Index was outside the bounds of the array

I am trying to

Remove()
or
Clear()
ToolbarItems
. Here is my code where I am creating
ToolbarItem
in 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);
}
}
}



Edit: when I included
this.ToolbarItems.Clear();
in
OpenWindow

method which initialise that another page opens and it works! Cleans
all toolbar items but unfortunately shows this error:

System.IndexOutOfRangeException: Index was outside the bounds of the array.



This items should disappear only for iOS as you see.
Here is my page class where I would like to
Remove()
these
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.
}
}
}


In this class I tried both approaches, but none work. Thank you for answers or suggestions.

Answer

First of all I really want to thank for all answers and suggestions I tried to implement both answers on my solution, but unfortunately unsuccessfully. Main reason that I wasn't focusing on class where I am implemented whole iOS toolbar and it was on my iOS project.

On iOS toolbar I just wrote simple if statement:

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