.net - RichTextbox SelectionStart 返回错误的索引

标签 .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

最佳答案

我不知道这是否是您问题的真正答案,但我使用这个简单的技巧来检索与文本相关的光标索引:
TextRange range = new TextRange(Document.ContentStart, CaretPosition);int n = range.Text.Length;
我正在开发基于 WPF 富文本框的编辑器。由于实时格式化(如突出显示关键字等)真的很慢,我在另一个线程中创建了一个新文档。在这个线程中,文本在适当的运行中被格式化,而不是将它们格式化为富文本框段落的一部分。完成后,新的将替换原来的。工作得非常好且令人难以置信的快(至少与 MS 方式相比)。

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

关于.net - RichTextbox SelectionStart 返回错误的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988539/

相关文章:

c# - 为什么 .NET 中的 $ 多行正则表达式不匹配 CRLF?

wpf - 使用 DataTemplate 将 View 连接到 ViewModel

MySQL查询主要非数字值

bash - 从后面 awk 一个巨大的日志文件直到时间戳

java - .NET 等效或替代 Java 的 GlyphVector?

C# 为什么其中一些使用委托(delegate)和泛型的方法没有启动?

c# - 如何在 WPF 中更改鼠标光标的指向位置

WPF ComboBox.Selected 附加事件。存在还是不存在?

c# - 什么时候服务器GC会被忽略?

c# - 什么 WPF C# 控件类似于 C++ 中的 CWnd?