Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Attaching a Command to the WP7 Application Bar

DZone's Guide to

Attaching a Command to the WP7 Application Bar

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

One of the biggest problems that I’ve seen with people creating WP7 applications is how do you bind the application bar to a Relay Command. If your using MVVM then this is particular important. Let’s examine the code that one might add to start with. 
<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
        <shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="/icons/appbar.questionmark.rest.png" Text="About">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding DisplayAbout, Mode=OneWay}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
 
        </shell:ApplicationBarIconButton>
        <shell:ApplicationBar.MenuItems>
            <shell:ApplicationBarMenuItem x:Name="menuItem1" Text="MenuItem 1"></shell:ApplicationBarMenuItem>
            <shell:ApplicationBarMenuItem x:Name="menuItem2" Text="MenuItem 2"></shell:ApplicationBarMenuItem>
        </shell:ApplicationBar.MenuItems>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Everything looks right. But we quickly notice that we have a squiggly line under our Interaction.Triggers. The problem is that the object is not a FrameworkObject. This same code would have worked perfect if this were a normal button.

image

OK. Point has been proved. Let’s make the ApplicationBar support Commands. So, go ahead and create a new project using MVVM Light. If you want to check out the source and work along side this tutorial then click here

7 Easy Steps to have binding on the Application Bar using MVVM Light (I might add that you don’t have to use MVVM Light to get this functionality, I just prefer it.)

image

1) Download MVVM Light if you don’t already have it and install the project templates. It is available at http://mvvmlight.codeplex.com/.

2) Click File-New Project and navigate to Silverlight for Windows Phone. Make sure you use the MVVM Light (WP7) Template.

SNAGHTML1683fc7d

3) Now that we have our project setup and ready to go let’s download a wrapper created by Nicolas Humann here, it is called Phone7.Fx. After you download it then extract it somewhere that you can find it. This wrapper will make our application bar/menu item bindable.

4) Right click References inside your WP7 project and add the .dll file to your project.

image

image

5) In your MainPage.xaml you will need to add the proper namespace to it. Don’t forget to build your project afterwards.

xmlns:Preview="clr-namespace:Phone7.Fx.Preview;assembly=Phone7.Fx.Preview"

6) Now you can add the BindableAppBar to your MainPage.xaml with a few lines of code. 

<Preview:BindableApplicationBar x:Name="AppBar" BarOpacity="1.0"  >
    <Preview:BindableApplicationBarIconButton Command="{Binding DisplayAbout}" IconUri="/icons/appbar.questionmark.rest.png" Text="About" />
    <Preview:BindableApplicationBar.MenuItems>
        <Preview:BindableApplicationBarMenuItem  Text="Settings" Command="{Binding InputBox}" />
    </Preview:BindableApplicationBar.MenuItems>
</Preview:BindableApplicationBar>
So your final MainPage.xaml will look similar to this: NOTE: The AppBar will be located inside of the Grid using this wrapper.  
<!--LayoutRoot contains the root grid where all other page content is placed-->
<Grid x:Name="LayoutRoot"
      Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
 
    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel"
                Grid.Row="0"
                Margin="24,24,0,12">
        <TextBlock x:Name="ApplicationTitle"
                   Text="{Binding ApplicationTitle}"
                   Style="{StaticResource PhoneTextNormalStyle}" />
        <TextBlock x:Name="PageTitle"
                   Text="{Binding PageName}"
                   Margin="-3,-8,0,0"
                   Style="{StaticResource PhoneTextTitle1Style}" />
    </StackPanel>
 
    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentGrid"
          Grid.Row="1">
 
        <TextBlock Text="{Binding Welcome}"
                   Style="{StaticResource PhoneTextNormalStyle}"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   FontSize="40" />
 
    </Grid>
    <Preview:BindableApplicationBar x:Name="AppBar" BarOpacity="1.0"  >
        <Preview:BindableApplicationBarIconButton Command="{Binding DisplayAbout}" IconUri="/icons/appbar.questionmark.rest.png" Text="About" />
        <Preview:BindableApplicationBar.MenuItems>
            <Preview:BindableApplicationBarMenuItem  Text="Settings" Command="{Binding InputBox}" />
        </Preview:BindableApplicationBar.MenuItems>
    </Preview:BindableApplicationBar>
</Grid>
7) Let’s go ahead and create the RelayCommands and write them up to a MessageBox by editing our MainViewModel.cs file.
public class MainViewModel : ViewModelBase
 {
     public string ApplicationTitle
     {
         get
         {
             return "MVVM LIGHT";
         }
     }
 
     public string PageName
     {
         get
         {
             return "My page:";
         }
     }
 
     public string Welcome
     {
         get
         {
             return "Welcome to MVVM Light";
         }
     }
 
     public RelayCommand DisplayAbout
     {
         get;
         private set;
     }
 
     public RelayCommand InputBox
     {
         get;
         private set;
     }
 
     /// <summary>
     /// Initializes a new instance of the MainViewModel class.
     /// </summary>
     public MainViewModel()
     {
         if (IsInDesignMode)
         {
             // Code runs in Blend --> create design time data.
         }
         else
         {
             DisplayAbout = new RelayCommand(() =>
                                                 {
                                                     MessageBox.Show("About box called!");
                                                 });
             InputBox = new RelayCommand(() =>
                                             {
                                                 MessageBox.Show("settings button called");
                                             });
         }
     }
If you run the project now you should get something similar to this (notice the AppBar at the bottom): 

SNAGHTML16881ecc

Now if you hit the question mark then you will get the following MessageBox:

image

The MenuItem works as well so for Settings:

SNAGHTML17405cd8

image

As you can see, its pretty easy to add a Command to the ApplicationBar/MenuItem. If you want to look through the full source code then click here





Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:

Published at DZone with permission of Michael Crump. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}