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?
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)