本文介绍了GetPositionAtOffset 仅对文本等效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有 GetPositionAtOffset() 等效的 漂亮 解决方案,它只计算文本插入位置而不是所有符号?

Is there a pretty solution of a GetPositionAtOffset() equivalent which only counts text insertion positions instead of all symbols?

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);
}

直到现在我都是这样解决"的

Until now i "solved" it this way

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;
}

推荐答案

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

As far as I'm aware, there isn't. My suggestion is that you create your own GetPositionAtOffset method for this purpose. You can check which PointerContext the TextPointer is adjacent to by using:

TextPointer.GetPointerContext(LogicalDirection);

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

To get the next TextPointer which points to a different PointerContext:

TextPointer.GetNextContextPosition(LogicalDirection);

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

Some sample code I used in a recent project, this makes sure that the pointer context is of type Text, by looping until one is found. You could use this in your implementation and skip an offset increment if it is found:

// for a TextPointer start

while (start.GetPointerContext(LogicalDirection.Forward) 
                             != TextPointerContext.Text)
{
    start = start.GetNextContextPosition(LogicalDirection.Forward);
    if (start == null) return;
}

希望你能利用这些信息.

Hopefully you can make use of this information.

这篇关于GetPositionAtOffset 仅对文本等效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 02:23