简体   繁体   中英

Manipulating Application Bars in Windows Phone 8.1 XAML from Code Behind

This might be a trivial beginner question and I have found quite a bit of related information for Windows and Silverlight apps but nothing that would directly help me. I'm writing a Windows Phone 8.1/WinRT app in C# and XAML, and I would like to programmatically modify application bars created in XAML. For instance, there is a button I want to include in debug builds only, using preprocessor directives in code behind.

In the following XAML code I'm creating a BottomAppBar with two buttons. How can I create the second button (AppBarAddSampleItemsButton) including all properties in code behind?

<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>

Here is a sample code creating an AppBarButton in the code behind and adding it to BottomAppBar of the current Page :

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

Edit - as for Binding (again from the top of my head, so you will have to check this) this should probably work:

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

More about DataBinding at MSDN .

After some digging around on the Windows Phone dev center, I found this page: How to change app bar icon buttons and menu items dynamically for Windows Phone . Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM