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



在我的应用程序中,我想在运行时添加应用程序栏。我有一个包含应用程序栏名称和图像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"
        }
    }

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

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);
                }
            }

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

相关内容

  • 没有找到相关文章

最新更新