I want to style a TabItem‘s “focus rectangle“. I’ve learned I can do this using FocusVisualStyle. The problem is that FocusVisualStyle creates a sepearate visual tree for an adorner that is drawn on top of the control. I use complex semi-transparent controls and drop-shadow effects, and I need to show the rectangle under certain elements that are part of the TabItem.Template.
I’ve found on MSDN that I can use IsKeyboardFocused combined with trigger to achieve what I need. However further research have shown this is not correct, because:
Keyboard focus refer to the element that is currently receiveing keyboard input. It doesn’t mean the focus is set via a keyboard navigation.
One of the possible workaround might be:
You can listen to key_down events to check whether an navigation key is pressed. WPF controls do this internally to display the FocusVisualStyle.
Is there any other, easier way to achieve what I’m trying to do? I’m not really into creating code behind, listening for events and handling all of these many different navigation keys and shortcuts.
By default, FrameworkElement checks what the last input device was in an override for OnGotKeyboardFocus. If the last input device was a keyboard, then it shows the FocusVisualStyle.
You can accomplish the same thing by adding a handler for the GotKeyboardFocus event and checking if
InputManager.Current.MostRecentInputDevice is KeyboardDevice.You’d probably want to add an attached dependency property so you can still use a Trigger, say IsFocusVisualVisible. You’d set it to true in your GotKeyboardFocus handler, if the last input device was the keyboard, and set to false in a handler for LostKeyboardFocus.