protected bool HasFocus()
{
DependencyObject focused =
#if SILVERLIGHT
FocusManager.GetFocusedElement() as DependencyObject;
#else
// For WPF, check if the element that has focus is within the control, as
// FocusManager.GetFocusedElement(this) will return null in such a case.
IsKeyboardFocusWithin ? Keyboard.FocusedElement as DependencyObject : FocusManager.GetFocusedElement(this) as DependencyObject;
#endif
while(focused != null)
{
if(ReferenceEquals(focused, this))
{
return true;
}
// This helps deal with popups that may not be in the same
// visual tree
DependencyObject parent = VisualTreeHelper.GetParent(focused);
if(parent == null)
{
// Try the logical parent.
FrameworkElement element = focused as FrameworkElement;
if(element != null)
{
parent = element.Parent;
}
}
focused = parent;
}
return false;
}