How to Do Command Binding for Application Bar with AppBarUtils in XAML?

Well, you have two options:

  1. use AppBarItemCommand directly
  2. or if you favor the built-in InvokeCommandAction, you can use it together with AppBarItemTrigger instead

Assuming you have an application bar defined as follows:

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem Text="clear"/>
        </shell:ApplicationBar.MenuItems>
        <shell:ApplicationBarIconButton
            IconUri="/icons/appbar.add.rest.png"
            Text="add"/>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

With AppBarItemCommand, you can bind the “add” button to the “AddCommand” property of your view model as follows:

<i:Interaction.Behaviors>
    <AppBarUtils:AppBarItemCommand
        Id="add" Command="{Binding AddCommand}"/>
</i:Interaction.Behaviors>

All you need to do is tell AppBarItemCommand which application bar button you want it to target by providing its text and what command you want to bind.

For the second option,  wrap the built-in InvokeCommandAction in the AppBarItemTrigger as follows:

<i:Interaction.Triggers>
    <AppBarUtils:AppBarItemTrigger Id="clear">
        <ec:InvokeCommandAction Command="{Binding ClearCommand}"/>
    </AppBarUtils:AppBarItemTrigger>
</i:Interaction.Triggers>

The difference between the above two options is that AppBarItemCommand will hook into the CanExecute method and CanExecuteChanged event of Command object and automatically set the status of application bar button accordingly. In short, AppBarItemCommand should be considered whenever possible.

For application bar menu item, simply specify MenuItem as the value of Type for AppBarItemCommand or AppBarItemTrigger. If you don’t specify a value for this property, it defaults to Button, which is what you have seen in the above code.

For a complete sample code, please visit http://appbarutils.codeplex.com/

Advertisements
Tagged

2 thoughts on “How to Do Command Binding for Application Bar with AppBarUtils in XAML?

  1. grockland says:

    Thanks for taking care of a problem for MVVM developers required to build an app for Windows Phone 8.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: