I’d like to provide you with a SilverBullet™, a small snippet of Silverlight, a class or namespace hidden in the silverlight .NET framework, to help you out in times of need. It’s not to learn, but something to keep in your pocket. Just remember it’s there and you’re safe.
There are situations where you want to know which UI element has focus. One way of doing this is handling the GotFocus and LostFocus events. These events are only raised when an element gets or looses focus, and are handled asynchronously. When you want to know what element has focus in other situations or if you need to get the focus synchronously, you can use the FocusManager class which can be found in the System.Windows.Input namespace.
The FocusManager class has only one static method:
public static Object GetFocusedElement();
The GetFocusedElement method often returns a Control, but may return null if the browser windows doesn’t have focus or if there are no true Control elements in the UI.
Using the FocusManager is easy. Here’s a small example of a possible usage:
var focusedElement = FocusManager.GetFocusedElement() as Control;
if (focusedElement != null)
Output.Text = focusedElement.Name;
One last note: The FocusManager class is also available in the “normal” .NET Framework 3.0 or later.