Reputation: 2309
Is there a UWP alternative for WPF's IsKeyboardFocusWithin property? If not, how would you go about getting whether the focus is within itself.
I would prefer not manually walking down the Visual Tree checking each element if it is focused...
Upvotes: 4
Views: 238
Reputation: 21919
FocusManager.GetFocusedElement will ID the focused element. You can then walk up the Visual Tree with VisualTreeHelper.GetParent to see if it's a child of the control you're interested in. Walking up will be much lighter weight than checking the entire tree child-node-by-node.
Something like:
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;
}
Upvotes: 3