Application bars play an important role in the UI of many phone applications. An application bar can contain up to four buttons (and five menu items) giving the user quick and easy access to the app’s most commonly used features:

image

Each button is an instance of ApplicationBarIconButton, and the ApplicationBarIconButton class exposes a property named IsEnabled that allows buttons to be enabled and disabled.

Let’s say that you want to disable one of these buttons in response to something the user does in your application. For example, maybe you want to disable the Save button after the user clicks it to save whatever he or she is working on. If you try doing it this way, you’re in for a rude surprise:

 

// MainPage.xaml

<shell:ApplicationBar IsVisible="True">

  <shell:ApplicationBarIconButton x:Name="AddButton" … />

  <shell:ApplicationBarIconButton x:Name="SaveButton" Click="OnSaveButtonClicked" … />

  <shell:ApplicationBarIconButton x:Name="RefreshButton" … />

  <shell:ApplicationBarIconButton x:Name="SettingsButton" … />

</shell:ApplicationBar>

 

// MainPage.xaml.cs

private void OnSaveButtonClicked(object sender, EventArgs e)

{

    SaveButton.IsEnabled = false;

}

 

The code compiles just fine, but it throws a NullReferenceException at run-time because SaveButton isn’t automatically initialized with a reference to the Save button.

So how do you disable an application bar button in code? By doing this:

 

// MainPage.xaml

<shell:ApplicationBar IsVisible="True">

  <shell:ApplicationBarIconButton x:Name="AddButton" … />

  <shell:ApplicationBarIconButton x:Name="SaveButton" Click="OnSaveButtonClicked" … />

  <shell:ApplicationBarIconButton x:Name="RefreshButton" … />

  <shell:ApplicationBarIconButton x:Name="SettingsButton" … />

</shell:ApplicationBar>

 

// MainPage.xaml.cs

private void OnSaveButtonClicked(object sender, EventArgs e)

{

    (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = false;

}

 

It’s not pretty, but it’s the way it is. And now that you know, you won’t lose an hour of development time the first time you run into it.