GetPositionAtOffset仅相当于文本?

Mar*_*air 6 wpf richtextbox wpf-controls

是否有一个相当的解决方案GetPositionAtOffset()只计算文本插入位置而不是所有符号?

C#中的动机示例:

TextRange GetRange(RichTextBox rtb, int startIndex, int length) {
    TextPointer startPointer = rtb.Document.ContentStart.GetPositionAtOffset(startIndex);
    TextPointer endPointer = startPointer.GetPositionAtOffset(length);
    return new TextRange(startPointer, endPointer);
}
Run Code Online (Sandbox Code Playgroud)

编辑:直到现在我以这种方式"解决"它

public static TextPointer GetInsertionPositionAtOffset(this TextPointer position, int offset, LogicalDirection direction)
{
    if (!position.IsAtInsertionPosition) position = position.GetNextInsertionPosition(direction);
    while (offset > 0 && position != null)
    {
        position = position.GetNextInsertionPosition(direction);
        offset--;
        if (Environment.NewLine.Length == 2 && position != null && position.IsAtLineStartPosition) offset --; 
    }
    return position;
}
Run Code Online (Sandbox Code Playgroud)

Jes*_*osh 2

据我所知,没有。我的建议是您为此目的创建自己的 GetPositionAtOffset 方法。您可以使用以下方法检查 TextPointer 与哪个 PointerContext 相邻:

TextPointer.GetPointerContext(LogicalDirection);
Run Code Online (Sandbox Code Playgroud)

要获取指向不同 PointerContext 的下一个 TextPointer:

TextPointer.GetNextContextPosition(LogicalDirection);
Run Code Online (Sandbox Code Playgroud)

我在最近的一个项目中使用了一些示例代码,这通过循环直到找到指针上下文来确保指针上下文是文本类型。您可以在实现中使用它,并在发现偏移增量时跳过它:

// for a TextPointer start

while (start.GetPointerContext(LogicalDirection.Forward) 
                             != TextPointerContext.Text)
{
    start = start.GetNextContextPosition(LogicalDirection.Forward);
    if (start == null) return;
}
Run Code Online (Sandbox Code Playgroud)

希望您能利用这些信息。