2

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

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

4

2 回答 2

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;
}
于 2009-11-05T11:38:42.820 回答
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;

}

于 2014-03-31T07:50:07.200 回答