Reputation: 570
How to get the keyboard focus is anywhere within the element or its visual tree child elements in Silverlght?
Upvotes: 1
Views: 197
Reputation: 189505
There are two possible solutions depending on your scenario (we usually prefer more detail in a question).
First you can use the FocusManager.GetFocusedElement()
static method to get the element that currently has the focus. You could then use the VisualTreeHelper
to determine if the element is with the your element. I would normally use an extension class to make using VisualTreeHelper
easier. Mine is found here. With that class present. Then:-
public static bool IsFocusIn(DependencyObject element)
{
DependendyObject focusedElement = FocusManager.GetFocusedElement() as DependencyObject;
if (focusedElement != null)
{
return focusedElement.Ancestors().Any(e => e == element);
}
return false;
}
The second approach is to add event handlers to the GotFocus
and LostFocus
events of your element. You can then track whenever the focus enters or leaves any control within your element.
Upvotes: 3