How can I disable the default RichTextBox command for Ctrl+1?

久未见 提交于 2019-12-25 06:46:57

问题


Snoop shows that the command is "ApplySingleSpace", but when I try disabling it via the method described in this article . Like this:

<RichTextBox.CommandBindings>
     <CommandBinding 
       Command="ApplySingleSpace" 
       CanExecute="BlockTheCommand"/>
   </RichTextBox.CommandBindings>

.

  private void BlockTheCommand(object sender,
     CanExecuteRoutedEventArgs e)
   {
     e.CanExecute = false;
     e.Handled = true;
   }

My app crashes because there is no ApplySingleSpace command. ApplySingleSpace is not in the EditingCommands either.

What am I missing?


回答1:


Unfortunately that will not work for me. The reason I am trying to disable the command is that I have a KeyBinding in a higher nested view that is not firing because the CTRL+1 gesture is being swallowed by the richtextbox which has keyboardfocus.

How about overwriting that KeyBinding with a custom command that does what you want instead of trying to somehow disable it?

<RichTextBox.InputBindings>
    <KeyBinding Command="local:YourCommands.Cmd1" Gesture="CTRL+1" />
<RichTextBox.InputBindings>

Taken from this question.




回答2:


Using the code from this answer
How can I programmatically generate keypress events in C#? to refire all events on PreviewKeyDown other than those you want handled by the richtextbox seems to work for me. (I only need Ctrl-C for copy). Of course you could make it so it only refires Ctrl-1 if that's what you need.


private void logKeyHandler(object sender, KeyEventArgs e)
{
    if (!(Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.C))
    {
        e.Handled = true;
        var routedEvent = Keyboard.KeyDownEvent; 
        this.RaiseEvent(
            new KeyEventArgs(
            Keyboard.PrimaryDevice, 
            PresentationSource.FromDependencyObject(this),
            0,
            e.Key) { RoutedEvent = routedEvent }
        );
    }
  }
 



回答3:


What about trying with the gesture instead...

        <RichTextBox.InputBindings>
            <KeyBinding Command="BlockTheCommand" Gesture="CTRL+1" />
        </RichTextBox.InputBindings>


来源:https://stackoverflow.com/questions/4630842/how-can-i-disable-the-default-richtextbox-command-for-ctrl1

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