BackKeyPress and LostFocus Colliding

Category : Windows Phone 7
Date : November 23, 2010

I’m working on a Windows Phone 7 app and ran into an issue that I just couldn’t figure out.  I was trapping the LostFocus event on a TextBox and finding that by handling the LostFocus event I was losing the case where the user hit the Back Key since that actually triggered the LostFocus event event first.  Peter Torr came to rescue with a code snippet that allowed me to handle that special case.  I’m posting here so others can benefit.

In my case all I needed was the ability to figure out if the reason the control lost focus was the result of a Back Key press.  The code snippet below also provides for other scenarios like the user tapped outside the textbox or on another control.

    private void textbox_LostFocus(object sender, RoutedEventArgs e)

{
object focusedElement = FocusManager.GetFocusedElement();
if (focusedElement == null)
{
whoHasFocus.Text = "User tapped outside of textbox";
}
else if (focusedElement == this)
{
whoHasFocus.Text = "SIP Dismissed";
}
else if (focusedElement is FrameworkElement)
{
whoHasFocus.Text = (focusedElement as FrameworkElement).Name + " has focus";
}
else
{
whoHasFocus.Text = "Magic 8-ball says....";
}
}

@