Find the parent RichTextBox from the focused hyperlink inside

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:

// inside DropDownButton.cs
protected override void OnLostFocus( RoutedEventArgs e )
{
    base.OnLostFocus( e );
    if (CloseOnLostFocus && !DropDown.IsFocused()) CloseDropDown();
}

// inside static class ControlExtensions.cs
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)
        {
            // can happen when potentialSubControl is technically
            // not part of the visualTree
            // for example when FocusManager.GetFocusedElement()
            // returned a focused hyperlink (System.Windows.Documents.Hyperlink)
            // from within a text area
            parent = null;
        }
        if (parent == null) {
            FrameworkElement element = potentialSubControl as FrameworkElement;
            if (element != null) parent = element.Parent;
        }
    }
    return false;
}

[] : Hyperlink DependencyObject, DependencyObjects FrameworkElements. - Silverlight.

0

Source: https://habr.com/ru/post/1618168/


All Articles