How do I move the caret a certain number of positions in a WPF RichTextBox?

…衆ロ難τιáo~ 提交于 2019-12-19 00:58:13

问题


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.


回答1:


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:

 rtb.CaretPosition = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
rtb.CaretPosition.InsertTextInRun(text);

Note that caret's LogicalDirection property may (and has to) be changed by this; it is not enough to simply create correct TextPointer.




回答2:


Use the GetInsertionPosition() method on the CaretPosition TextPointer. This will allow you to insert the text before the caret.

private void rtb_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Tab)
    {
        rtb.CaretPosition.GetInsertionPosition(LogicalDirection.Backward).InsertTextInRun("    ");
        e.Handled = true;
    }
}



回答3:


To test, you could try forcing the movement yourself:

rtb.CaretPosition = rtb.Document.ContentEnd;

If that works, you'll probably have to implement additional logic for situations where the tab is not at the end of the content.



来源:https://stackoverflow.com/questions/2497291/how-do-i-move-the-caret-a-certain-number-of-positions-in-a-wpf-richtextbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!