2012-07-16 63 views
0

我一直在試圖編寫一個程序來搜索richTextBox中的單詞。我做了大部分,但看起來我錯過了一些東西。我想爲找到的單詞着色,所以我寫了以下內容:C#中的TextRange和RichTextBox WPF

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     richTextBox1.SelectAll(); 
     string words = richTextBox1.Selection.Text; // to get the the whole text 

     int length = words.Length;     // length of text 

     string search = textBox1.Text;    // the word being searched for 
     int search_length = search.Length; 


     int index =0;        // to go through the text 
     int endIndex = 0;       // the end of the got word 

     // pointer to the begining and the ending of the word which will be colored. 
     TextPointer start_pointer, end_pointer; 

     if(length>0 &&search_length>0)    // text exists 
     while(index<length-search_length) 
     { 
      index = words.IndexOf(search, index); 
      if (index < 0) // not found 
       break; 
      endIndex = index+search.Length-1;  // last char in the word 
      start_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(index, LogicalDirection.Forward); 
      end_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(endIndex + 1, LogicalDirection.Forward); 

      TextRange got = new TextRange(start_pointer, end_pointer); 

//just for debugging 
      MessageBox.Show("start =" + index + " end =" + endIndex + " " + got.Text); 

      got.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue)); 
      index =endIndex+1; 
     } 

第一個單詞是彩色的。但接下來的話不是(例如,如果文本是「上學,我會去市場上」,搜索詞「go」,然後我按下搜索按鈕,結果會是着色第一個「去」,但第二個不會着色)。

我估計發生這種情況是因爲textRange無法正常工作,或者TextPointer中出現問題。此外,索引和endIndex是正確的 - 我已經測試過它們。

我感謝您的幫助。

+0

你需要檢查你的邏輯似乎過於複雜,特別是計算索引。並使用IndexOf方法 – HichemSeeSharp 2012-07-16 21:05:18

回答

0

試試這個代碼:

TextRange rangeText = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd); 
rangeText.Text = "Text1 "; 
rangeText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue); 
rangeText.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold); 

TextRange rangeWord = new TextRange(richTextBox.Document.ContentEnd,  richTextBox.Document.ContentEnd); 
rangeWord.Text = "word "; 
rangeWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red); 
rangeWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular); 

TextRange rangeTextOne = new TextRange(richTextBox.Document.ContentEnd,  richTextBox.Document.ContentEnd); 
rangeTextOne.Text = "Text2 "; 
rangeTextOne.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue); 
rangeTextOne.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);