Display an AppBarButton on the left inside a CommandBar

Display an AppBarButton on the left inside a CommandBar

With Windows 8.1, it was easy to add a button to the left side or the right side of a CommandBar using PrimaryCommands and SecondaryCommands.

But Windows 10 uses a different template for CommandBar, similar to the one used by Windows Phone 8.1:

  • primary commands as a button (aligned to the right)
  • secondary commands as a menuitem

Sans titre

So, here is the question: How can I align a button to the left?

Have a button to the left can be very interesting for many scenarios, one of them is the hamburger menu, an other one is to highlight a specific feature, like I did on 6tag.

Sans titre

So, how can I do that?

In order to do that, you need to use the property Content of the CommandBar, this property will allow you to add one FrameworkElement to the left, like for example… an AppBarItem!

Note: contrary to a lot of other controls, the default property for children nodes is not Content but PrimaryCommand, this is IMO the reason why nobody finds it.

<Page.BottomAppBar>
<CommandBar>
<CommandBar.Content>
<AppBarButton Icon="Home"/>
</CommandBar.Content>
<AppBarButton Icon="Delete"/>
<AppBarButton Icon="Calendar"/>
</CommandBar>
</Page.BottomAppBar>

Sans titre

But if I need many buttons?

As I said, Content property needs a FrameworkElement, so you can easily use a StackPanel and include many AppBarItem on it:


<Page.BottomAppBar>
<CommandBar>
<CommandBar.Content>
<StackPanel>
<AppBarButton Icon="Home"/>
<AppBarButton Icon="Like"/>
</StackPanel>
</CommandBar.Content>
<AppBarButton Icon="Delete"/>
<AppBarButton Icon="Calendar"/>
</CommandBar>
</Page.BottomAppBar>

What about the label of the AppBarItem?

Sans titre

A bug is remaining, if you use a label, it will be visible even if the CommandBar is not opened, to fix that, we will bind the property AppBarItem.IsCompact to the CommandBar.IsOpen property. Of course, we need to invert the value of the boolean.


<AppBarItem IsCompact="{Binding IsOpen,ElementName=MyCommandBar,Converter={StaticResource InvertBooleanConverter}}"/>

What about globalization and right-to-left languages?

I’ve tested the same code with arabian language for example, and no problems, the Content is aligned to the right whereas PrimaryCommands are on the left

Sans titre

 

Conclusion

This property was not easy to find, due to a poor MSDN documentation

Capture

but whatever, don’t hesitate to use it in your apps, and for example think about it when you want to use an hamburger menu on your phone app, buttons on the top are not always easy to use with some phones (1520, 625, 950 XL)

Comments are closed.