Customization:
I have a RichTextBox containing a hyperlink and DropDownButtonsomewhere else in my interface. Now, when I click the DropDownopen button and then click elsewhere in my user interface, it DropDownis implemented to close and checks if it still has keyboard focus so that it can focus again ToggleButtonafter DropDown, as intended.
Problem:
When I click inside mine, RichTextBoxI came across InvalidOperationExceptionone called by my method to check the ownership of the focus. The call VisualTreeHelper.GetParent(potentialSubControl)works fine for all elements that are part of VisualTree. Apparently focused Hyperlink(returnable FocusManager.GetFocusedElement()) is not part of VisualTree and therefore is an invalid input for GetParent(). Well, how can I find the parent (logical parent or visual parent) of a hyperlink in mine RichTextBox?
My method for determining focus ownership:
protected override void OnLostFocus( RoutedEventArgs e )
{
base.OnLostFocus( e );
if (CloseOnLostFocus && !DropDown.IsFocused()) CloseDropDown();
}
public static bool IsFocused( this UIElement control )
{
DependencyObject parent;
for (DependencyObject potentialSubControl =
FocusManager.GetFocusedElement() as DependencyObject;
potentialSubControl != null; potentialSubControl = parent)
{
if (object.ReferenceEquals( potentialSubControl, control )) return true;
try { parent = VisualTreeHelper.GetParent(potentialSubControl); }
catch (InvalidOperationException)
{
parent = null;
}
if (parent == null) {
FrameworkElement element = potentialSubControl as FrameworkElement;
if (element != null) parent = element.Parent;
}
}
return false;
}
[]
: Hyperlink DependencyObject, DependencyObjects FrameworkElements. - Silverlight.