Reputation: 16166
Is there any way to tell whether a control (specifically a System.Windows.Controls.TextBox) is focused in Silverlight? I'm looking for something like the following (what you would see in a regular .Net application):
textBox.Focused
This seems like something simple and trivial to leave out from a control, and yet I can't find an answer anywhere.
Update
A slightly more elegant solution, incorporating Rob's answer, is to create an extension method like so:
public static bool IsFocused( this Control control )
{
return FocusManager.GetFocusedElement() == control;
}
Upvotes: 16
Views: 8826
Reputation: 6146
As soon as you have a control consisting of more than one input element (which needs to have focus for handling user input) asking the FocusManager won't do the trick anymore. Try this:
private bool HasFocus { get; set; }
protected override void OnGotFocus( RoutedEventArgs e )
{
base.OnGotFocus( e );
HasFocus = true;
}
protected override void OnLostFocus( RoutedEventArgs e )
{
base.OnLostFocus( e );
HasFocus = false;
}
Upvotes: 0
Reputation: 15621
You have to use FocusManager
bool b = FocusManager.GetFocusedElement() == textBox;
Upvotes: 27