Tech Off Thread

4 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Swapping application bars dynamically on Windows Phone 8

Back to Forum: Tech Off
  • User profile image
    Mauricio Feijo

    Its 5:20 AM and I woke up at 4:45 with an approach that would make my life easier. Had to code it. It worked beautifully, so I had to blog it to get opinions and help others.

     

    The app I am working on have 2 states, and on each state the user will see a different set of buttons and menu items on the app bar.

    I didnt want to write the app bar completely in C#, for I always choose XAML over C# when possible. Otherwise we would just write it all in C#! 

    I started by creating the buttons as app resources in APP.XAML. Note that some buttons overlap both app bars, so this approach avoids having 2 buttons that do the same thing.

    <Application.Resources>
    <shell:ApplicationBarIconButton x:Key="ChooseButton" IconUri="/Images/ChooseButton.png" Text="choose">
    ...
    </shell:ApplicationBarIconButton>
    

     I then added both app bars to APP.XAML resource as well, referencing the buttons as StaticResources

    <shell:ApplicationBar x:Key="AppBarState1" IsVisible="True" Opacity="0.5">
    <shell:ApplicationBar.Buttons>
    <StaticResource ResourceKey="ChooseButton" />
    ...
    </shell:ApplicationBar.Buttons>
    </shell:ApplicationBar>
     
    

    Now on the page code behind comes the inevitable C#. I feel this is perfectly OK as it has to do with procedure and intelligence rather then declaration.

    
    var chooseButton = (ApplicationBarIconButton)App.Current.Resources["ChooseButton"];
    chooseButton.Click += ChooseButtonClick;
    ...
    

    After setting up the button handlers we will decide which app bar to show and assign it to the page's ApplicationBar property:

    ApplicationBar = (IApplicationBar)App.Current.Resources["AppBarState1"]; // choose based on app state
     
    

     I hope this helps some folks. If you think of a more elegant or appropriate way of achieving the same , please let us know.

  • User profile image
    Dr Herbie

    @Mauricio Feijo: Nice solution -- will this work in WP7 or just WP8?

    My WP7 app used C# to change the app bar buttons (see example on StackOverflow), but your solution is much more elegant.  Well done!

    Herbie

  • User profile image
    Mauricio Feijo

    Thank Herbie!

    I am not really sure if it will work on  WP7. Hopefully it will. If you try let us know the results.

  • User profile image
    whoknows

    Wondering if you could provide a sample  to download and see how it works. My email is rezyde@gmail.com if you want to shoot it over to me, i've been pulling my hair out with this.

     

    many thanks,

    fernando

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.