如何在 WPF RichTextBox 中将插入符号移动一定数量的位置? [英] How do I move the caret a certain number of positions in a WPF RichTextBox?
问题描述
我想将插入符号移动到当前插入符号所在位置的右侧.我注册了 PreviewKeyDown
,并在捕获 Tab 键时调用 InsertTextInRun()
,如下所示:
I want to move the caret 4 positions to the right of where my caret currently is. I'm registered for PreviewKeyDown
, and calling InsertTextInRun()
when the tab key is captured, like so:
private void rtb_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
rtb.CaretPosition.InsertTextInRun(" ");
e.Handled = true;
}
}
问题是在调用 InsertTextInRun()
后插入符号保持原位.它不会移动到新文本的末尾,这是我想要的行为.我该怎么做?
The problem is that the caret stays in place after the call to InsertTextInRun()
. It does not move to the end of the new text, which is the behavior I want. How would I do this?
顺便说一句 - 是的,我知道 RichTextBox
上的 AcceptsTab
属性.我选择忽略 is 并滚动我自己的选项卡功能,因为使用 AcceptsTab
进行选项卡会产生令人讨厌的副作用,即在后续行中缩进文本,这不是我想要的.
As an aside - yes, I know about the AcceptsTab
property on RichTextBox
. I'm choosing to ignore is and roll my own tab functionality because tabbing with AcceptsTab
has a nasty side effect of indenting text on subsequent lines, which is not what I want.
推荐答案
我刚刚遇到了同样的问题.似乎最终插入符号的位置取决于它在插入之前的移动方式.
I've just bumped into the same problem. It seems final caret position depends on which way it was moving right before the insert.
以下代码确保(3.5sp1)插入后,光标将位于插入文本的右侧:
Following code makes sure (3.5sp1) that after insert, the cursor will be to the right of the inserted text:
rtb.CaretPosition = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
rtb.CaretPosition.InsertTextInRun(text);
请注意,插入符号的 LogicalDirection 属性可能(并且必须)由此更改;仅仅创建正确的 TextPointer 是不够的.
Note that caret's LogicalDirection property may (and has to) be changed by this; it is not enough to simply create correct TextPointer.
这篇关于如何在 WPF RichTextBox 中将插入符号移动一定数量的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!