按代码添加AppBar(Windows 8.1,C#)

时间:2013-10-24 08:54:16

标签: c# windows-runtime windows-store-apps windows-8.1 commandbar

在我的场景中,我想为所有Windows 8.1应用页面编写BasePage。 在此BasePage中,应该创建TopAppBar

其实我有:

public CommandBar TopCommandBar
{
    get
    {
        // Check if a TopAppBar exists
        if (this.TopAppBar != null) return this.TopAppBar.Content as CommandBar;

        var appBar = new AppBar();
        this.TopAppBar = appBar;
        var top = this.TopAppBar.Content as CommandBar;
        if (top == null)
        {
            topCommandBar = new CommandBar();
            this.TopAppBar.Content = topCommandBar;
        }
        return this.TopAppBar.Content as CommandBar;
    }
}

此代码运行良好。但是稍后在我的BaseClass中,我想添加AppBarButton

if (ShowCloseButton)
{
    var closeBtn = new AppBarButton();
    closeBtn.Icon = new SymbolIcon(Symbol.Clear);
    closeBtn.Label = "Close";
    closeBtn.Click += closeBtn_Click;
    this.TopCommandBar.PrimaryCommands.Insert(0, closeBtn);
}

直到我点击鼠标右键两次,closeBtn才会显示TopAppBar

表示我第一次点击右键 - > TopAppBar出现但内部没有按钮。

然后我再次点击右键 - > TopAppBar保持打开状态,按钮显示其全部功能。

2 个答案:

答案 0 :(得分:2)

是的,我同意这看起来像个错误。我在代码生成的路径中看到了同样的事情。经过调查,看起来AppBar.IsOpen在右键单击或滑动时切换为true,但CommandBar.IsOpen仍为false。这个修复对我有用:

BottomAppBar.Opened + =(o,args)=> {(this.BottomAppBar.Content as CommandBar).IsOpen = true; };

答案 1 :(得分:0)

您也可以直接将AppBar用作CommandBar:

    CommandBar appBar = this.BottomAppBar as CommandBar;
    if (appBar == null)
    {
        appBar = new CommandBar();
        this.BottomAppBar = appBar;
    }

    var btnAbout = new AppBarButton() { Icon = new SymbolIcon(Symbol.Help), Label = "About" };
    btnAbout.Click += btnAbout_Click;
    appBar.SecondaryCommands.Add(btnAbout);