How to add contextual commands to an app bar (XAML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

Hide app bar commands that are relevant only in certain contexts until they are relevant. For example, you might have image editing commands that are useful only when an image is selected. Or, you might have a global app bar with commands that are relevant only on certain pages. These examples show several ways you can add contextual commands to an app bar.

Roadmap: How does this topic relate to others? See:

What you need to know

Technologies

Prerequisites

Instructions

Step 1: Add a command button to a command bar (Windows 8.1)

Windows 8.1: This step applies only to Windows 8.1. For Windows 8, see steps 3-5.

You can add commands to a CommandBar in your code-behind file. You typically do this to add commands that apply only when an item is selected, or when you share a CommandBar between pages and have commands that apply to only one page. Adding the command in the code of the page that the command applies to makes it easier to hook the command up to elements in that page. Here, you add a command to a shared CommandBar when the user navigates to a page, and remove it when the user navigates away from the page.

For more info about sharing an app bar, see How to share an app bar across pages and XAML AppBar control sample.

When a user navigates to the page, add the command to the CommandBar.

  1. Add a CommandBar as the bottom app bar to your app. For more info, see Quickstart: Adding app bars.

    Here, you add a bottom app bar with a single button defined in XAML.

        <Page.BottomAppBar>
            <CommandBar x:Name="bottomAppBar">
                <AppBarButton Icon="Sort" Label="Sort" Click="AppBarButton_Click"/>
            </CommandBar>
        </Page.BottomAppBar>
    
  2. When a user navigates to the page, create an AppBarSeparator to add to the CommandBar.

  3. Create an AppBarButton to add to the CommandBar.

  4. Set the Icon and Label for the AppBarButton.

  5. Register the Click event handler.

  6. Add the button to the CommandBar.

void Page1_Loaded(object sender, RoutedEventArgs e)
{
    bottomAppBar.PrimaryCommands.Insert(0, new AppBarSeparator());

    AppBarButton addButton = new AppBarButton();
    addButton.Icon = new SymbolIcon(Symbol.Add);
    addButton.Label = "Add";
    addButton.Click += AppBarButton_Click;
    bottomAppBar.PrimaryCommands.Insert(0, addButton);
}

Step 2: Remove the command button from the command bar (Windows 8.1)

Windows 8.1: This step applies only to Windows 8.1. For Windows 8, see steps 3-5.

When a user navigates away from the page, remove the command from the AppBar

  1. Un-register the Click event handler.
  2. Remove the AppBarButton from the CommandBar.
  3. Remove the AppBarSeparator from the CommandBar.
void Page1_Unloaded(object sender, RoutedEventArgs e)
{
    CommandBar bottomCommandBar = this.BottomAppBar as CommandBar;
    if (bottomCommandBar != null)
    {
        AppBarButton b = bottomCommandBar.PrimaryCommands[0] as AppBarButton;
        b.Click -= AppBarButton_Click;

        // Remove AppBarButton.
        bottomCommandBar.PrimaryCommands.RemoveAt(0);
        // Remove AppBarSeparator.
        bottomCommandBar.PrimaryCommands.RemoveAt(0);
    }
}

Step 3: Show and hide commands (Windows 8)

Windows 8: This step applies only to Windows 8. For Windows 8.1, see steps 1-2. In Windows 8.1, AppBarButtonStyle is deprecated and replaced with AppBarButton controls.

To show and hide a group of commands in an AppBar you can use the Visibility property. This is how you typically control contextual commands based on user selection in a page.

  1. Add an app bar to your app. For more info, see Quickstart: Adding app bars.

  2. Name commands or groups that you show and hide.

    1. To show and hide an individual command, name its command button.
    2. Or, to show and hide a group of commands, put them in a named container.

    In this example, the "Pin" and "Unpin" commands are put in a StackPanel named pinCommands. The pinCommands group is initially collapsed.

    <AppBar IsOpen="True" IsSticky="True">
        <Grid>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                <StackPanel x:Name="pinCommands" Orientation="Horizontal"
                            Visibility="Collapsed">
                    <Button Style="{StaticResource UnpinAppBarButtonStyle}" 
                            Click="Button_Click"/>
                    <Button Style="{StaticResource PinAppBarButtonStyle}" 
                            Click="Button_Click"/>
                    <Rectangle Height="50" Width="2" Fill="LightGray"/>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <Button Style="{StaticResource FavoriteAppBarButtonStyle}" 
                            Click="Button_Click"/>
                    <Button Style="{StaticResource SearchAppBarButtonStyle}" 
                            Click="Button_Click"/>
                </StackPanel>
            </StackPanel>
        </Grid>
    </AppBar>
    
  3. Set the Visibility property of the named command or container to show or hide it.

    Here, you use a ToggleSwitch to show and hide the pinCommands group. In a typical app, you might show and hide commands based on a user selection or some other interaction with your app.

    void AppBarSample::SnippetsPage::ToggleSwitch_Toggled(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
        ToggleSwitch^ toggle = safe_cast<ToggleSwitch^>(sender);
    
        if (toggle->IsOn == true)
        {
            pinCommands->Visibility = Windows::UI::Xaml::Visibility::Visible;
        }
        else
        {
            pinCommands->Visibility = Windows::UI::Xaml:: Visibility::Collapsed;
        }
    }
    
    private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
    {
        ToggleSwitch toggle = (ToggleSwitch)sender;
    
        if (toggle.IsOn == true)
        {
            pinCommands.Visibility = Visibility.Visible;
        }
        else
        {
            pinCommands.Visibility = Visibility.Collapsed;
        }
    }
    
    Private Sub ToggleSwitch_Toggled(sender As Object, e As RoutedEventArgs)
        Dim toggle = DirectCast(sender, ToggleSwitch)
    
        If toggle.IsOn = True Then
            pinCommands.Visibility = Windows.UI.Xaml.Visibility.Visible
        Else
            pinCommands.Visibility = Windows.UI.Xaml.Visibility.Collapsed
        End If
    End Sub
    

Here's what the app bar looks like with the commands hidden.

Here's what the app bar looks like with the commands shown.

Step 4: Add a command button to an app bar (Windows 8)

Windows 8: This step applies only to Windows 8. For Windows 8.1, see steps 1-2. In Windows 8.1, AppBarButtonStyle is deprecated and replaced with AppBarButton controls.

You can add commands to an AppBar in your code-behind file. You typically do this when you share an AppBar between pages and have commands that apply to only one page. Adding the command in the code of the page that the command applies to makes it easier to hook the command up to elements in that page. Here, you add a command to a shared AppBar when the user navigates to a page, and remove it when the user navigates away from the page.

For more info about sharing an app bar, see How to share an app bar across pages and XAML AppBar control sample.

When a user navigates to the page, add the command to the AppBar.

  1. Add an app bar to your app. For more info, see Quickstart: Adding app bars.

    Here, you add a bottom app bar with a single button defined in XAML.

    <Page.BottomAppBar>
        <AppBar x:Name="bottomAppBar" IsSticky="True">
            <Grid>
                <StackPanel x:Name="rightPanel" 
                            Orientation="Horizontal" HorizontalAlignment="Right">
                    <Button Style="{StaticResource AppBarButtonStyle}" 
                            Content="&#xE174;" 
                            AutomationProperties.Name="Sort"
                            AutomationProperties.AutomationId="SortButton"
                            Click="SortMenuButton_Click" />
                </StackPanel>
            </Grid>
        </AppBar>
    </Page.BottomAppBar>
    
  2. When a user navigates to the page, create the command button to add to the AppBar.

  3. Apply an app bar button style to the button.

  4. Register the Click event handler.

  5. Add the button to the AppBar.

Button^ addButton;
Windows::Foundation::EventRegistrationToken buttonClickHandler;

void SnippetsPage::OnNavigatedTo(NavigationEventArgs^ e)
{
    (void) e;    // Unused parameter
                    
    if (rightPanel)
    {    
         // Create the button to add
         addButton = ref new Button();
    
         //Apply the button style so that it looks like an AppBar button
         addButton->Style = safe_cast<Windows::UI::Xaml::Style^>(App::Current->Resources->Lookup("AddAppBarButtonStyle"));
             
        // Add the Click handler for the new button
         buttonClickHandler = addButton->Click += 
             ref new Windows::UI::Xaml::RoutedEventHandler(this, &AppBarSample::SnippetsPage::Button_Click);
    
         // Add the button to the AppBar
         rightPanel->Children->Append(addButton);
    }

}

void AppBarSample::SnippetsPage::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    // Perform action here.
}
Button addButton = null;

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Add a button to an AppBar.
   
    if (rightPanel != null)
    {
        // Create the button to add
        addButton = new Button();

        // Apply the button style so that it looks like an AppBar button
        addButton.Style = (Style)App.Current.Resources["AddAppBarButtonStyle"];

        // Add the Click handler for the new button
        addButton.Click += Button_Click;

        // Add the button to the AppBar
        rightPanel.Children.Add(addButton);
    }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Perform action here.
}
Dim addButton As Button = Nothing
Protected Overrides Sub OnNavigatedTo(e As Navigation.NavigationEventArgs)

    If rightPanel IsNot Nothing Then
        ' Create the button to add
        addButton = New Button()

        ' Apply the button style so that it looks like an AppBar button
        addButton.Style = App.Current.Resources("AddAppBarButtonStyle")

        ' Add the Click handler for the new button
        AddHandler addButton.Click, AddressOf Button_Click

        ' Add the button to the AppBar
        rightPanel.Children.Add(addButton)
    End If
End Sub

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    ' Perform action here.
End Sub

Step 5: Remove the command button from the app bar (Windows 8)

Windows 8: This step applies only to Windows 8. For Windows 8.1, see steps 1-2. In Windows 8.1, AppBarButtonStyle is deprecated and replaced with AppBarButton controls.

When a user navigates away from the page, remove the command from the AppBar

  1. Un-register the Click event handler.
  2. Remove the button from the AppBar.
void SnippetsPage::OnNavigatingFrom(NavigatingCancelEventArgs^ e)
{
    // Unhook the Click event handler for the button
    addButton->Click -= buttonClickHandler;
    
    // Add the button to the AppBar
    uint32 index = rightPanel->Children->IndexOf(addButton, &index);
    rightPanel->Children->RemoveAt(index);
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
    if (rightPanel != null)
    {
        // Unhook the Click event handler for the button
        addButton.Click -= Button_Click;

        // Remove the button from the AppBar
        rightPanel.Children.Remove(addButton);
    }
}
Protected Overrides Sub OnNavigatingFrom(e As Navigation.NavigatingCancelEventArgs)
    If rightPanel IsNot Nothing Then

        ' Unhook the Click event handler for the button
        RemoveHandler addButton.Click, AddressOf Button_Click

        ' Remove the button from the AppBar
        rightPanel.Children.Remove(addButton)

    End If
End Sub

XAML AppBar control sample

Quickstart: Adding app bars

AppBar