0

I have an application bar in my Windows Phone 8.1 Silverlight app. It contains one ApplicationBarButton and when the user scrolls to a certain point in the LongListSelector another button is added to the ApplicationBar like this:

for (int i = 0; i < 1; i++)
{
     ApplicationBarIconButton scrollToToday = new ApplicationBarIconButton();
     scrollToToday.Text = "idag";
     scrollToToday.IconUri = new Uri("/Assets/AppBar/today_dark.png", UriKind.Relative);
     parent.ApplicationBar.Buttons.Add(scrollToToday);
}

When the user then scrolls back to the original point start point I remove it with:

parent.ApplicationBar.Buttons.RemoveAt(1);

But the app crashes when it reaches that code line when the app is started since the app starts in the original starting point and then there is no second button to remove. I think it has to do with that I first must check that if the ApplicationBar contains more than one button it is okay to remove the button at index 1. But how do I do this?

2 Answers2

2

First, you don't need a for loop to add the button, since you're adding only one:

 ApplicationBarIconButton scrollToToday = new ApplicationBarIconButton();
 scrollToToday.Text = "idag";
 scrollToToday.IconUri = new Uri("/Assets/AppBar/today_dark.png", UriKind.Relative);
 parent.ApplicationBar.Buttons.Add(scrollToToday);

Then, if I understand correctly, you want to remove the last button if there's more than one. If so, you can use this code:

var count = parent.ApplicationBar.Buttons.Count;

if (count >= 2)
{
    parent.ApplicationBar.Buttons.RemoveAt(count - 1);
}

(storing count in a temporary variable isn't mandatory, I just did this to increase readability)

Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
0

Check the number of buttons first, you need Linq for that:

 using System.Linq;

 ...

 if(parent.ApplicationBar.Buttons.Count() > 1)
      parent.ApplicationBar.Buttons.RemoveAt(1);
thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
  • 'System.Collections.IList' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Collections.IList' could be found @KooKiz answer is the correct one for me –  Apr 24 '15 at 10:30
  • as I stated, you need Linq, add this to the top of your file `using System.Linq;` – thumbmunkeys Apr 24 '15 at 11:54