Here’s another quick one I ran into while testing my application. I need to submit data to a web service and wait for a response. While they phone is talking to the web service, I don’t want the user to send the same request twice. Initiating the send takes place on the app bar.
We need to disable the app bar button. If you attempt to use the control name you assign to the button it will throw a null reference exception. Not a very good UX. My initial solution that I put in place and held my nose was similar to:
((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Enabled = false;
Don’t get me started on what I don’t like about that approach, ok?
I came across an instance where I needed to disable two buttons, I just couldn’t handle the smell of:
((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Enabled = false;((ApplicationBarIconButton)ApplicationBar.Buttons[1]).Enabled = false;
And decided to do something about it. My solution is a simple extension method that looks like:
namespace Microsoft.Phone.Shell
{
public static class ApplicationBarHelpers
{
public static void Enable(this IApplicationBar appBar)
{
appBar.IsMenuEnabled = true;
foreach (var obj in appBar.Buttons)
{
var button = obj as ApplicationBarIconButton;
if (button != null)
button.IsEnabled = true;
}
}
public static void Disable(this IApplicationBar appBar)
{
appBar.IsMenuEnabled = false;
foreach (var obj in appBar.Buttons)
{
var button = obj as ApplicationBarIconButton;
if (button != null)
button.IsEnabled = false;
}
}
}
}
Something still smells above…should be able to get rid of some lines of code but don’t want to get too side tracked. Kudo’s and a mention to anyone that can do a little cleanup.
Just include the using Microsoft.Phone.Shell to pickup the namespace within your .cs file and you can do the following:
ApplicationBar.Enable();
and
ApplicationBar.Disable();
Which I think is much cleaner.
-twb