KeyBinding gesture “Ctrl+1” in RichTextBox doesn't work

别来无恙 提交于 2019-12-10 10:36:10

问题


There is a strange difference when binding commands to Ctrl+N gestures in WPF. Some but not all of these gestures are ignored, while the rest are ok. Did anyone else experience this behavior by any chance?

Window XAML structure is very simple: command binding, input binding, and a DockPanel with Menu and RichTextBox. After testing, the problem appears only when input focus is in RichTextBox.

For the test, Window input binding was defined for all numeric keys as shown below. As a result, Ctrl+1, Ctrl+2, and Ctrl+5 wouldn't do anything, while Ctrl+3, 4, 6-9, and 0 are working just fine. Alt+1, Alt+2 are working ok as well.

 <Window.InputBindings>
  <KeyBinding Command="me:MainWindow.MyRC" Gesture="CTRL+0" />
  <KeyBinding Command="me:MainWindow.MyRC" Gesture="CTRL+1" />
  ...
  <KeyBinding Command="me:MainWindow.MyRC" Gesture="CTRL+9" />
 </Window.InputBindings>

Problem cause

As Andy pointed out, RichTextBox already binds some gestures to internal commands. When this gesture is handled inside RTB it won't be passed to the Window level. This is somewhat hard to detect when there is no apparent effect of key stroke on the text in RTB.

Solution 1

If command only makes sense in the context of RTB - move input binding inside it to override default command binding:

<RichTextBox.InputBindings>
    <KeyBinding Command="me:WindowBindingTest.MyRC1" Gesture="CTRL+1" />
    <KeyBinding Command="me:WindowBindingTest.MyRC2" Gesture="CTRL+2" />
    <KeyBinding Command="me:WindowBindingTest.MyRC5" Gesture="CTRL+5" />
</RichTextBox.InputBindings>

Solution 2

If commmand has "larger scope" and should be available even when input focus is outside of RTB - remove gesture binding from unused default RTB commands:

<RichTextBox.InputBindings>
    <KeyBinding Command="NotACommand" Gesture="CTRL+1" />
    <KeyBinding Command="NotACommand" Gesture="CTRL+2" />
    <KeyBinding Command="NotACommand" Gesture="CTRL+5" />
</RichTextBox.InputBindings>

回答1:


It looks like the RichTextBox already defines a binding for a command using Ctrl+1 ("ApplySingleSpace"). Therefore it is likely handling the command and not letting it route up to the Window.

You might be able to work around this by adding an InputBinding to the RichTextBox, but since you'd also need it on the Window for when other controls are in focus, that's not a very good solution.



来源:https://stackoverflow.com/questions/4200553/keybinding-gesture-ctrl1-in-richtextbox-doesnt-work

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