当AllowTab设置为false时,将选项卡插入WPF RichTextBox

时间:2009-11-05 04:51:10

标签: wpf richtextbox tabbing

我正在尝试解决当AllowTab属性设置为false时如何将制表符插入WPF RichTextBox。

是否有允许此操作的快捷键?我宁愿不必在工具栏上添加一个特殊的按钮,或者告诉用户他们必须复制并粘贴一个......

2 个答案:

答案 0 :(得分:6)

好的,到目前为止我能想到的最好的是拦截后面代码中的keydown事件:

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;
}

答案 1 :(得分:0)

以下代码适用于我。

  private void RichTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
         if (e.Key != Key.Tab)      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("        ");
 richTextBox.CaretPosition = caretPosition;
 e.Handled = true;

}