简体   繁体   English

如何获取Windows Phone应用程序栏中的按钮数量

[英]How to get number of buttons in an Windows Phone application bar

I have an application bar in my Windows Phone 8.1 Silverlight app. 我的Windows Phone 8.1 Silverlight应用程序中有一个应用程序栏。 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: 它包含一个ApplicationBarButton并且当用户滚动到LongListSelector的某个点时,将另一个按钮添加到ApplicationBar如下所示:

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? 我认为这与我必须首先检查ApplicationBar包含多个按钮是否可以删除索引1上的按钮有关。但是我该怎么做?

First, you don't need a for loop to add the button, since you're adding only one: 首先,您不需要for循环来添加按钮,因为您只添加了一个:

 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) (在临时变量中存储count不是强制性的,我只是这样做以提高可读性)

Check the number of buttons first, you need Linq for that: 首先检查按钮数量,您需要使用Linq:

 using System.Linq;

 ...

 if(parent.ApplicationBar.Buttons.Count() > 1)
      parent.ApplicationBar.Buttons.RemoveAt(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM