In a WPF key handler, can I programmatically change/override the key that was pressed?
As it states in the tit开发者_C百科le, we're trying to intercept one key and replace it with another. Think similar to key remapping.
Our specific usage is to change the left and right arrow keys to behave like Shift-Tab and Tab respectively.
Now I know I can intercept those and manually control the focus, but I'm trying to leverage as much of the built-in navigation behavior as possible. We just want to (also) use the arrow keys for that type of behavior.
Only thing I can think of is to swallow the event, then re-throw it with the correct parameters but I'm concerned that will interfere with things like key release, repeating, etc.
I'm also open to other ways of doing this if this isn't actually possible. Again, our goal is to leverage the built-in behaviors, just via other keys.
As your goal is to map the arrow keys to do some keyboard tab navigation, you should map the appropriate commands to the keys and implement them. The ComponentCommands.MoveFocusForward
and ComponentCommands.MoveFocusBack
commands would be appropriate here as that's what we're doing, moving focus forward to the next or back to the previous control.
Here's an example how you could do all that.
First you'll need to bind the commands to your keys.
<Window.CommandBindings>
<CommandBinding Command="ComponentCommands.MoveFocusForward" Executed="MoveFocusForward_Executed" />
<CommandBinding Command="ComponentCommands.MoveFocusBack" Executed="MoveFocusBack_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Command="ComponentCommands.MoveFocusForward" Key="Right" />
<KeyBinding Command="ComponentCommands.MoveFocusBack" Key="Left" />
</Window.InputBindings>
Then implement the handlers.
private static bool RequestFocusChange(FocusNavigationDirection direction)
{
var focused = Keyboard.FocusedElement as UIElement;
if (focused != null)
{
return focused.MoveFocus(new TraversalRequest(direction));
}
return false;
}
private void MoveFocusForward_Executed(object target, ExecutedRoutedEventArgs e)
{
RequestFocusChange(FocusNavigationDirection.Next);
}
private void MoveFocusBack_Executed(object target, ExecutedRoutedEventArgs e)
{
RequestFocusChange(FocusNavigationDirection.Previous);
}
精彩评论