WPF的IsKeyboardFocusWithin属性的UWP替代

时间:2019-01-31 00:03:19

标签: c# xaml uwp focus

WPF的IsKeyboardFocusWithin属性是否有UWP替代品?如果没有,您将如何获取焦点是否在其内部。

我宁愿不要手动沿着可视树手动检查每个元素是否集中……

1 个答案:

答案 0 :(得分:2)

FocusManager.GetFocusedElement将标识焦点元素。然后,您可以使用VisualTreeHelper.GetParent在可视树上行走,以查看它是否是您感兴趣的控件的子级。与逐个节点逐节点检查整个树相比,行走的重量要轻得多。

类似的东西:

    bool IsKeyboardFocusWithin(UIElement element)
    {
        UIElement focused = FocusManager.GetFocusedElement() as UIElement;

        while (focused != null)
        {
            if (focused == element)
            {
                return true;
            }
            focused = VisualTreeHelper.GetParent(focused) as UIElement;
        }
        return false;
    }