Application Bar Buttons Are Null

Windows Phone From Scratch #50

In a recent posting, I demonstrated how easy it is to add buttons to the phone’s Application Bar.

I went back to that application to disable the “faster” button when the maximum speed was reached. I named the button and then tried to access that button in code. Much to my surprise, the button was null. It was always null.

I’ve recently been turning to search rather than to the standard documentation as my first line of defense when I run into unexpected problems.  Thus, I entered “Windows Phone Application Bar Button Null” into Bing and the first result was a wonderful article on this very issue written by Laurent Bugnion (author of MVVM Light). 

He solves the problem elegantly, and I won’t repeat his work here, but I will walk you through the changes I made to the program.

I first opened the program and, following Laurent’s suggestion, I created an enumeration for the two buttons that were in place,

public enum ButtonTypes
   Slower = 0,
   Faster = 1


I created a method that retrieves the button from the ApplicationBar’s Buttons property, using an index and casting the result to be of type ApplicationBarIconButton.

 public ApplicationBarIconButton GetButton( 
       ButtonTypes whichButton )
    return ApplicationBar.Buttons[(int) whichButton] 
       as ApplicationBarIconButton;

Having retrieved the button, I could now set it to disabled if conditions were correct

if ( currentTS <= new TimeSpan( 0, 0, 0, 0, INCREMENT ) )
   GetButton( ButtonTypes.Faster ).IsEnabled = false;
   GetButton( ButtonTypes.Faster ).IsEnabled = true;

Problem solved, and quickly, thanks to Bing and Laurent. 

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in Essentials, Mini-Tutorial, WindowsPhone and tagged , . Bookmark the permalink.

4 Responses to Application Bar Buttons Are Null

Comments are closed.