【问题标题】:Manipulating Application Bars in Windows Phone 8.1 XAML from Code Behind从代码隐藏操作 Windows Phone 8.1 XAML 中的应用程序栏
【发布时间】:2014-10-07 12:09:39
【问题描述】:

这可能是一个微不足道的初学者问题,我找到了很多有关 Windows 和 Silverlight 应用程序的相关信息,但没有任何东西可以直接帮助我。我正在用 C# 和 XAML 编写一个 Windows Phone 8.1/WinRT 应用程序,我想以编程方式修改在 XAML 中创建的应用程序栏。例如,我只想在调试版本中包含一个按钮,在后面的代码中使用预处理器指令。

在下面的 XAML 代码中,我创建了一个带有两个按钮的 BottomAppBar。如何创建第二个按钮 (AppBarAddSampleItemsButton),包括后面代码中的所有属性?

<prism:VisualStateAwarePage.BottomAppBar>
    <CommandBar >
        <CommandBar.PrimaryCommands>
            <AppBarButton x:Uid="AppBarNewItemButton"
                          Label="New item"
                          Icon="Add" Command="{Binding GoToAddItemPageCommand}" />
        </CommandBar.PrimaryCommands>
        <CommandBar.SecondaryCommands>
            <AppBarButton x:Uid="AppBarAddSampleItemsButton"
                          Label="Add sample items"
                          Command="{Binding GoToAddSampleItemssPageCommand}" />
        </CommandBar.SecondaryCommands>
    </CommandBar>
</prism:VisualStateAwarePage.BottomAppBar>

【问题讨论】:

    标签: c# windows-runtime winrt-xaml windows-phone-8.1 commandbar


    【解决方案1】:

    这是一个示例代码,在后面的代码中创建一个AppBarButton,并将其添加到当前页面BottomAppBar

    private void AddButtonToAppBar()
    {
        AppBarButton buttonToAdd = new AppBarButton { Label = "Label", Icon = new SymbolIcon(Symbol.Help) };
        buttonToAdd.Click += async (sender, e) =>  await new MessageDialog("Button clicked").ShowAsync();
        // add button to Page's BottoAppBar
        (BottomAppBar as CommandBar).PrimaryCommands.Add(buttonToAdd);
    }
    

    编辑 - 至于 Binding (再次从我的脑海中,所以你必须检查这个)这应该可以工作:

    Binding myBind = new Binding();
    myBind.Path = new PropertyPath("GoToAddSampleItemssPageCommand");
    myBind.Source = DataContext;
    buttonToAdd.SetBinding(AppBarButton.CommandProperty, myBind);
    

    更多关于DataBinding at MSDN

    【讨论】:

    • 谢谢。看起来不错。但在尝试添加按钮时会抛出 NullReferenceException。似乎没有得到命令栏上的句柄。
    • @jerry 这将取决于您何时调用此方法 - 要使其工作,必须先创建 BottomAppBar。你在哪里调用这个方法?
    • 哎呀,即使我也应该想出那个。我在初始化页面之前调用了它。它现在完美运行。小细节:“Command”绑定怎么样?
    • @jerry 我添加了一个编辑,但你必须检查它 - 我没有时间测试它。
    • 谢谢你,罗马兹。你帮了我很多。
    【解决方案2】:

    在对 Windows Phone 开发中心进行了一番挖掘之后,我找到了这个页面:How to change app bar icon buttons and menu items dynamically for Windows Phone。希望对您有所帮助!

    【讨论】:

    • 谢谢,乔希。我认为这适用于 Silverlight 应用程序。
    猜你喜欢
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多