以编程方式添加应用程序栏时出现异常

时间:2012-12-25 09:17:53

标签: c# windows-phone-7 windows-phone-7.1 windows-phone-8 application-bar

在我的应用程序中,我想在运行时添加应用程序栏。我有一个包含应用程序栏名称和图像uri的列表。我必须根据列表添加应用程序栏。但是我得到一个例外“指定的参数超出有效值范围“。任何人都可以给我一个解决方案吗?下面是我的代码。

public void createObjectsForApplicationbar(List<AppBarDetails> appbarList)
    {
        int i = 0;
        foreach (Others menus in appbarList)
        {                                                          
          UpdateAppbarButton(i, menus.menu_image, menus.name, true, ApplicationBarIconButton_Click);
          i++;
        }
        ShowButtons(menuNames1);
    }                                                                                 



private void UpdateAppbarButton(int index, string uriString, string text, bool visibility, EventHandler handler)
    {
        ApplicationBarIconButton button1 = null;
        this.ApplicationBar = new ApplicationBar();
        this.ApplicationBar.IsVisible = true;
        this.ApplicationBar.Opacity = 1;
        this.ApplicationBar.IsMenuEnabled = true;
        if (this.ApplicationBar.Buttons.Count > index)
        {
            button1 = this.ApplicationBar.Buttons[index] as ApplicationBarIconButton;
        }

        if (button1 != null)
        {
            {
                this.ApplicationBar.Buttons.Remove(button1);
            }
        }
        if (visibility == true)
        {
            button1 = new ApplicationBarIconButton(new Uri(uriString, UriKind.RelativeOrAbsolute));
            button1.Text = text;
            button1.Click += handler;
            this.ApplicationBar.Buttons.Insert(index, button1);// here i got the exception "Specified argument was out of the range of valid values when the value of  i=1"
        }
    }

1 个答案:

答案 0 :(得分:1)

你应该重新考虑你的条件的逻辑。

if (this.ApplicationBar.Buttons.Count > index)
            {
                button1 = this.ApplicationBar.Buttons[index] as ApplicationBarIconButton;

                this.ApplicationBar.Buttons.Remove(button1);

                if (visibility == true)
                {
                    button1 = new ApplicationBarIconButton(new Uri(uriString, UriKind.RelativeOrAbsolute));
                    button1.Text = text;
                    button1.Click += handler;
                    this.ApplicationBar.Buttons.Insert(index, button1);
                }
            }

            else
            // insert it anyway?
            {
                if (visibility == true)
                {
                    button1 = new ApplicationBarIconButton(new Uri(uriString, UriKind.RelativeOrAbsolute));
                    button1.Text = text;
                    button1.Click += handler;
                    this.ApplicationBar.Buttons.Add(button1);
                }
            }

不确定,你真正想要的是什么,但这样做没有例外。