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; } else { GetButton( ButtonTypes.Faster ).IsEnabled = true; }
Problem solved, and quickly, thanks to Bing and Laurent.
4 Responses to Application Bar Buttons Are Null