从列表中动态添加应用程序栏

时间:2012-12-25 15:15:52

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

我必须在运行时添加应用程序栏我已经尝试了一些代码并且对我来说不起作用任何人都可以建议我一个解决方案吗? 这是我的代码

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

    }

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;

            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

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


    }

当我运行此代码时,我只得到一个按钮作为输出,即使列表中有8个项目。我从stackoverflow 获得了此代码

1 个答案:

答案 0 :(得分:1)

每次添加按钮

时都不应创建新的ApplicationBar

删除此行:

this.ApplicationBar = new ApplicationBar();

this.ApplicationBar.Buttons.Add(Buttons[text]);

错了。您在此代码块中创建新按钮。所以你应该添加这个按钮。

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