【问题标题】:RichTextbox SelectionStart returns wrong indexRichTextbox SelectionStart 返回错误的索引
【发布时间】:2012-01-24 14:30:12
【问题描述】:

我需要像在 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

有什么想法吗?


* 编辑 * 第一个解决方案

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

''' <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

【问题讨论】:

  • RichTextBox 自动创建一个段落和一个运行(或类似的东西),因此非零索引。光标不在开头,而是在第一段的第一次运行。
  • 再次感谢 H.B.为了您的快速响应。你有什么解决办法吗?
  • 不,否则我会发布答案。
  • 尝试在TextPointer类对象上使用GetPointerContext方法来验证它的值是否为TextPointerContext.Text。您还可以在此处找到有关RichTextBox 选择的更多信息:stackoverflow.com/questions/1454440/…。它是关于选择文本而不是检查选择,但它可能对您有所帮助(如果您想获取文本选择的开始和结束位置)。如果您想了解更多信息,请向我们提供有关您希望这部分代码做什么的更多详细信息。
  • 感谢卢卡斯的回答。搜索字符的方式不是很好,但很有效。我对我的解决方案不满意(在上面),我会等待。也许有人知道如何使用 RTB 内部实现。

标签: .net wpf text richtextbox


【解决方案1】:

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

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

我正在开发基于 WPF 富文本框的编辑器。由于实时格式化(如突出显示关键字等)非常慢,我在另一个线程中创建了一个新文档。在这个线程中,文本在适当的运行中被格式化,而不是将它们格式化为 Richtextbox 段落的一部分。完成后,原始的将被新的替换。效果非常好,速度惊人(至少与 MS 方式相比)。

我希望这能给您一些灵感和/或想法。

【讨论】:

    猜你喜欢
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多