开发者

KeyBinding gesture "Ctrl+1" in RichTextBox doesn't work

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 structu开发者_开发问答re 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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜