wpfrichtextboxtabbing

Inserting a tab into a WPF RichTextBox when AllowTab is set to false


I am trying to work out how to insert a tab character into a WPF RichTextBox when the AllowTab attribute is set to false.

Is there a shortcut key that allows this? I would rather not have to resort to adding a special button to the toolbar or telling users that they must copy and paste one in ...


Solution

  • Okay, the best I can come up with so far is intercepting the keydown event in the code behind:

    private void RichTextBox_KeyDown(object sender, KeyEventArgs e)
    {
         if (e.Key != Key.Tab || 
             (Keyboard.Modifiers & ModifierKeys.Control) != ModifierKeys.Control)
                    return;
    
         var richTextBox = sender as RichTextBox;
         if (richTextBox == null) return;
    
         if (richTextBox.Selection.Text != string.Empty)
            richTextBox.Selection.Text = string.Empty;
    
         var caretPosition = richTextBox.CaretPosition.GetPositionAtOffset(0,
                               LogicalDirection.Forward);
    
         richTextBox.CaretPosition.InsertTextInRun("\t");
         richTextBox.CaretPosition = caretPosition;
         e.Handled = true;
    }