2009-06-11 10 views
2

私のSystem.Windows.Controls.RichTextBoxに、与えられた単語のTextRangeを探したいと思います。しかし、最初に見つかった単語の後ろに正しいPositionAtOffsetを与えているわけではありません。最初のものは正しいものであり、次に見つかった単語については、位置が正しくありません。私は正しい方法を使用していますか?RichTextBox内のTextRangeを見つける方法(2つのTextPointerの間)

ループ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

0

私は、それも動作するはずだと思います。

"find next"のようなものです。

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; 
    } 
関連する問題