09 Apr 2011

Windows Phone 7: Dynamic ApplicationBar

No Comments Silverlight and Windows Phone 7

One off the striking things about WP7 is how it tries to force developers to style apps. I don’t see this as a bad thing, and the ApplicationBar is one of the ways it does this. If your application uses a Pivot control, you may want to show a different menu depending on which PivotItem is selected. Unfortunately, the outermost control’s Applicati0onBar is the one which is shown. A relatively easy way to get around this is to define multiple ApplicationBars in the PhoneApplicationPage’s resources, then switch based on the selected index…

In the page’s resources section, add:

<phone:PhoneApplicationPage.Resources>
        <shell:ApplicationBar x:Key="appbarRecipes">
            <shell:ApplicationBarIconButton x:Name="appbarRecipesAddRecipe" IconUri="/Resources/Icons/light/appbar.add.png" Text="Add Recipe" Click="FireAddRecipe"/>
        </shell:ApplicationBar>
 
        <shell:ApplicationBar x:Key="appbarTools">
            <shell:ApplicationBarIconButton IconUri="/Resources/Icons/light/appbar.sync.png" Text="Synchronize" Click="ShowSync" />
            <shell:ApplicationBar.MenuItems>
                <shell:ApplicationBarIconButton IconUri="/Resources/Icons/light/appbar.wrench_plus_2.png" Text="Options" Click="ShowOptions"/>
                <shell:ApplicationBarIconButton IconUri="/Resources/Icons/light/appbar.help.png" Text="About" Click="ShowAbout" />
            </shell:ApplicationBar.MenuItems>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.Resources>

Then define a SelectionChanged handler for the Pivot control’s SelectionChanged event and load the right ApplicationBar dynamically according to which PivotItem has been selected.

        private void pvt_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (pvtMain.SelectedIndex) {
                case 0:
                    ApplicationBar = Resources["appbarRecipes"] as ApplicationBar;
                    break;
                case 1:
                    ApplicationBar = Resources["appbarTools"] as ApplicationBar;
                    break;
            }
        }
Tags:
written by
The author didn‘t add any Information to his profile yet.
No Responses to “Windows Phone 7: Dynamic ApplicationBar”

Leave a Reply