2009-06-11 75 views
2

在我的System.Windows.Controls.RichTextBox中,我想查找給定單詞的TextRange。但是,在第一個找到的單詞之後它沒有給我正確的PositionAtOffset。第一個是正確的,然後對於下一個發現的單詞,位置不正確。我使用正確的方法嗎?如何在RichTextBox中找到TextRange(在兩個TextPointers之間)

遍歷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); 

回答

11

代碼適於從樣品在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; 
} 

然後,您可以使用它,像這樣:

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

TextPointer.GetPositionAtOffset的偏移量是'符號'而不是字符,因此這段代碼通常不起作用。如果字符串單詞包含空格或非英語語言可能跨越UIElements,則很可能是這樣。 – Mark 2014-02-19 18:16:34

0

我認爲,它應該也可以。

這就像是「查找下一個」列表中的任何項目。

TextPointer FindWordsFromPosition(TextPointer position, IList<string> words) 
    { 
     var firstPosition = position; 
     while (position != null) 
     { 
      if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) 
      { 
       string textRun = position.GetTextInRun(LogicalDirection.Forward); 

       var indexesInRun = new List<int>(); 

       foreach (var word in words) 
       { 
        var index = textRun.IndexOf(word); 

        if (index == 0) 
         index = textRun.IndexOf(word, 1); 

        indexesInRun.Add(index); 
       } 

       indexesInRun = indexesInRun.Where(i => i != 0 && i != -1).OrderBy(i => i).ToList(); 

       if (indexesInRun.Any()) 
       { 
        position = position.GetPositionAtOffset(indexesInRun.First()); 
        break; 
       } 

       return firstPosition; 
      } 
      else 
       position = position.GetNextContextPosition(LogicalDirection.Forward); 
     } 

     return position; 
    } 
相關問題