RichTextbox SelectionStart返回错误的索引

时间:2012-01-24 14:30:12

标签: .net wpf text richtextbox

我需要在notepad.exe中向用户显示他在光标上的文本选择开始和长度。

选择长度没有问题,因为Richtextbox支持带有开始和结束的选择属性。

http://msdn.microsoft.com/en-us/library/system.windows.documents.textpointer.getoffsettoposition.aspx

但是如果我将光标设置在文档的第一个位置,我的RichTexbox的startindex总是2而不是0。 如果我清除整个文本,它就在0上。但是,如果我按SPACE然后按BACKSPACE,则文本框为空,但StartIndex的计数器位于2

有什么想法吗?

TB HyperTerminal Win7


*编辑* 第一个解决方案

好的,这是我的一个有效的解决方案。但我认为有更好的方法可以做到。

''' <summary>
    ''' Get the position of the cursor. Ignores all formatting characters like ENTER and PARAGRAPH. Just counts the visible characters.
    ''' </summary>
    ''' <param name="rtb">The richtextbox the value should be determined</param>
    ''' <returns>Index value of the cursor. 0 is at the first position. After position is behind characters "123" it would return the index 3.</returns>
    ''' <remarks>Watch out for performance, Use this methode in separated. Timo Böhme, 2012</remarks>
    Private Function GetPositionOfCursor(ByVal rtb As RichTextBox) As Integer
        Dim contentStart As TextPointer = rtb.Document.ContentStart
        Dim res As Integer = 0
        Dim CursorIndex As Integer = contentStart.GetOffsetToPosition(rtb.CaretPosition)
        Dim j As Integer = 0

        Do
            If j > CursorIndex Then Exit Do
            If contentStart.GetPositionAtOffset(1, LogicalDirection.Forward) Is Nothing Then
                Exit Do
            ElseIf contentStart.GetPointerContext(LogicalDirection.Backward) = TextPointerContext.Text Then
                res += 1
            End If

            contentStart = contentStart.GetPositionAtOffset(1, LogicalDirection.Forward)
            j += 1
        Loop

        Return res
    End Function

1 个答案:

答案 0 :(得分:2)

我不知道这是否是您问题的真实答案,但我使用这个简单的技巧来检索与文本相关的光标索引:

TextRange range = new TextRange(Document.ContentStart, CaretPosition);
int n = range.Text.Length;

我正在使用基于WPF richtextbox的编辑器。由于实时格式化(如突出显示关键字等)非常慢,我在另一个线程中创建一个新文档。在这个线程中,文本在适当的运行中被格式化,而不是将它们格式化为richtextbox的段落的一部分。完成后,原来的一个被新的替换。工作非常好,速度令人难以置信(至少与MS方式相比)。

我希望这会给你一些灵感和/或想法。

相关问题