Find the Parent RichTextBox from the Focused Hyperlink Within

旧巷老猫 提交于 2020-01-06 21:00:58

问题


The Setting: I have a RichTextBox containing a hyperink and a DropDownButton somewhere else in my UI. Now when I click the button's DropDown open and afterwards click somewhere else on my UI, the DropDown is implemented to close, and check if it still owns the keyboardfocus so it can set its ToggleButton to focused again after the DropDown collapsed as intended.

The Problem: When clicking inside my RichTextBox I will face an InvalidOperationException caused by my method to check focus ownership. The call to VisualTreeHelper.GetParent(potentialSubControl) works fine for all elements that are part of the VisualTree. Apparently the focused Hyperlink (returned by FocusManager.GetFocusedElement()) is not part of the VisualTree and therefore is invalid input to GetParent(). Well, how can I find the parent (either logical parent or visual parent) of a hyperlink within my 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;
}

[Edit] One potential idea to solve the issue: since Hyperlink is a DependencyObject I could try to access its inheritance context and find other DependencyObjects higher up in the tree and test them for being FrameworkElements. But I struggle to find any information about inheritance context in Silverlight.

来源:https://stackoverflow.com/questions/31816083/find-the-parent-richtextbox-from-the-focused-hyperlink-within

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!