是否有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);
}
编辑:直到现在我以这种方式“解决”了
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;
}
答案 0 :(得分:2)
据我所知,没有。我的建议是你为此创建自己的GetPositionAtOffset方法。您可以使用以下命令检查TextPointer与哪个PointerContext相邻:
TextPointer.GetPointerContext(LogicalDirection);
获取指向不同PointerContext的下一个TextPointer:
TextPointer.GetNextContextPosition(LogicalDirection);
我在最近的一个项目中使用的一些示例代码,这确保了指针上下文的类型是Text,通过循环直到找到一个。您可以在实现中使用它,如果找到则跳过偏移量增量:
// for a TextPointer start
while (start.GetPointerContext(LogicalDirection.Forward)
!= TextPointerContext.Text)
{
start = start.GetNextContextPosition(LogicalDirection.Forward);
if (start == null) return;
}
希望您可以利用这些信息。
答案 1 :(得分:0)
长时间无法找到解决此问题的有效方法。 下一段代码在我的案例中以最高性能运行。希望它也会对某人有所帮助。
TextPointer startPos = rtb.Document.ContentStart.GetPositionAtOffset(searchWordIndex, LogicalDirection.Forward);
startPos = startPos.CorrectPosition(searchWord, FindDialog.IsCaseSensitive);
if (startPos != null)
{
TextPointer endPos = startPos.GetPositionAtOffset(textLength, LogicalDirection.Forward);
if (endPos != null)
{
rtb.Selection.Select(startPos, endPos);
}
}
public static TextPointer CorrectPosition(this TextPointer position, string word, bool caseSensitive)
{
TextPointer start = null;
while (position != null)
{
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
string textRun = position.GetTextInRun(LogicalDirection.Forward);
int indexInRun = textRun.IndexOf(word, caseSensitive ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase);
if (indexInRun >= 0)
{
start = position.GetPositionAtOffset(indexInRun);
break;
}
}
position = position.GetNextContextPosition(LogicalDirection.Forward);
}
return start; }