如何在RichTextBox中找到TextRange(在两个TextPointers之间)

par*_*oir 2 c# wpf richtextbox

在我的System.Windows.Controls.RichTextBox中,我想找到给定单词的TextRange.但是,在第一个找到的单词后,它没有给我正确的PositionAtOffset.第一个是正确的,然后对于下一个找到的单词,位置不正确.我使用正确的方法吗?

循环遍历listOfWords

Word= listOfWords[j].ToString();

startPos = new TextRange(transcriberArea.Document.ContentStart, transcriberArea.Document.ContentEnd).Text.IndexOf(Word.Trim());

 leftPointer = textPointer.GetPositionAtOffset(startPos + 1, LogicalDirection.Forward);

rightPointer = textPointer.GetPositionAtOffset((startPos + 1 + Word.Length), LogicalDirection.Backward);
TextRange myRange= new TextRange(leftPointer, rightPointer);
Run Code Online (Sandbox Code Playgroud)

Bry*_*hle 12

MSDN上的样本改编的该代码将从指定位置找到单词.

TextRange FindWordFromPosition(TextPointer position, string word)
{
    while (position != null)
    {
        if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
        {
            string textRun = position.GetTextInRun(LogicalDirection.Forward);

            // Find the starting index of any substring that matches "word".
            int indexInRun = textRun.IndexOf(word);
            if (indexInRun >= 0)
            {
                TextPointer start = position.GetPositionAtOffset(indexInRun);
                TextPointer end = start.GetPositionAtOffset(word.Length);
                return new TextRange(start, end);
            }
        }

        position = position.GetNextContextPosition(LogicalDirection.Forward);
    }

    // position will be null if "word" is not found.
    return null;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以像这样使用它:

string[] listOfWords = new string[] { "Word", "Text", "Etc", };
for (int j = 0; j < listOfWords.Length; j++)
{
    string Word = listOfWords[j].ToString();
    TextRange myRange = FindWordFromPosition(x_RichBox.Document.ContentStart, Word);
}
Run Code Online (Sandbox Code Playgroud)