如何在 WPF RichTextBox 中将插入符号移动一定数量的位置?
我想将插入符号移动到当前插入符号位置的右侧 4 个位置。我注册了 PreviewKeyDown
,并在捕获 Tab 键时调用 InsertTextInRun()
,如下所示:
private void rtb_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
rtb.CaretPosition.InsertTextInRun(" ");
e.Handled = true;
}
}
问题是在调用 <代码>InsertTextInRun()。它不会移动到新文本的末尾,这是我想要的行为。我该怎么做?
顺便说一句 - 是的,我知道 RichTextBox
上的 AcceptsTab
属性。我选择忽略 is 并推出我自己的选项卡功能,因为使用 AcceptsTab
进行选项卡操作会产生令人讨厌的副作用,即在后续行上缩进文本,这不是我想要的。
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;
}
}
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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我刚刚遇到了同样的问题。看来最终插入符的位置取决于它在插入之前移动的方式。
以下代码确保 (3.5sp1) 在插入后,光标将位于插入文本的右侧:
请注意,插入符的 LogicalDirection 属性可能(并且必须)由此更改;仅仅创建正确的 TextPointer 是不够的。
I've just bumped into the same problem. It seems final caret position depends on which way it was moving right before the insert.
Following code makes sure (3.5sp1) that after insert, the cursor will be to the right of the inserted text:
Note that caret's LogicalDirection property may (and has to) be changed by this; it is not enough to simply create correct TextPointer.
使用 GetInsertionPosition() 方法在 CaretPosition TextPointer 上。这将允许您在插入符号之前插入文本。
Use the GetInsertionPosition() method on the CaretPosition TextPointer. This will allow you to insert the text before the caret.
为了测试,您可以尝试自己强制移动:
如果有效,您可能需要针对选项卡不在内容末尾的情况实现额外的逻辑。
To test, you could try forcing the movement yourself:
If that works, you'll probably have to implement additional logic for situations where the tab is not at the end of the content.