Skip to main content Skip to footer

Allow Tab Navigation While AllowTab is set to False in RichTextBox for WPF Edition

Background:

Setting C1RichTextBox’s AcceptsTab property to false, ’Tab’ key starts functioning as Navigation key. This prevents from entering Tab character into text.

Steps to Complete:

To perform both functions using the Tab key, create a key combination (Shift + Tab key) to allow the “Tab” key to perform navigation. When creating key combination, use the KeyDown event. While handling this event, the caret location needs to be detected and the word at that location needs to be found. Having access to the word, modify its content by manually adding a Tab character.

private void rtb_KeyDown(object sender, KeyEventArgs e)
{
       if (e.Key == Key.Tab && Keyboard.Modifiers == ModifierKeys.Shift && handleFlag)
       {
           var point = rtb.Selection.Start;
           var run = point.Element as C1Run;
           if (run != null)
           {
               var text = run.Text;
               var startPoint = point.Offset;
               var endPoint = point.Offset;
               while (startPoint > 0 && char.IsLetterOrDigit(text, startPoint - 1))
                   startPoint--;
               endPoint -= 1;
               var currentWord = new C1TextRange(point.Element, startPoint, endPoint - startPoint + 1);
               currentWord.Text += "\t";
               handleFlag = false;
               e.Handled = true;
           }
       }
       else
       {
           handleFlag = true;
       }
}

Ruchir Agarwal