2014-02-22 5 views
3

RichTextBox에서 한 줄을 강조 표시하려고합니다. 내 시도는 텍스트에서 라인의 위치를 ​​얻은 다음 text.Substring(offset, word.Length)을 나타내는 TextRange를 작성하는 것이 었습니다. 하지만 여하튼 RichTextBox는 이전 줄의 마지막 2 글자와 실제 줄의 일부 문자 또는 실제 줄의 일부만 강조 표시합니다. 나의 현재의 접근 방식은 이것이다 :RichTextBox에서 한 줄 강조 표시

public void SelectLine(string text) 
    { 
     int i = new TextRange(editor.Document.ContentStart, editor.Document.ContentEnd).Text.IndexOf(text); 
     TextPointer start = editor.Document.ContentStart.GetPositionAtOffset(i); 
     TextPointer end = start.GetPositionAtOffset(text.Length); 

     TextRange r = new TextRange(start, end); 

     if (r != null) 
     { 
      r.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red); 
      r.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White); 
     } 
    } 

그리고 이것은 내가 두 번째 행을 선택하려고 할 때와 같은 모습입니다 : 왜 이런 일이

enter image description here

, 당신은 어떤 생각을 가지고 있습니까를?

편집 : 현재의 접근 방식에는 WPF RichTextBox가 포함되어 있습니다.

답변

2

많은 것을 검색 한 후에 마침내이 솔루션으로 돌아 왔습니다. 주어진 라인을 세면서 문서 블록을 반복합니다. 작은 단락 편집기를 작성했기 때문에 전체 단락이나 줄만 강조 표시되는지는 상관하지 않습니다. 오류를 표시하고 주어진 소스에서 강조 표시해야합니다. 이것은 내 강조 표시 코드입니다 :

public void SelectLine(int line) 
    { 
     int c = 0; 
     TextRange r; 

     foreach (var item in editor.Document.Blocks) 
     { 
      if (line == c) 
      { 
       r = new TextRange(item.ContentStart, item.ContentEnd); 
       if (r.Text.Trim().Equals("")) 
       { 
        continue; 
       } 
       r.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red); 
       r.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.White); 
       return; 
      } 
      c++; 
     } 
    } 

주어진 블록이 비어 있는지 여부를 반복하여 검사합니다. 그렇다면 다음 블록이 조사됩니다.

0

많이 연구 한 결과 해결책을 찾았습니다.

TextRange Mytextrange2; 
private void Selectline(int line) 
    { 
     // STEP1: set CaretPosition to fist position of richtextbox (Vietnamese: đưa Carretposition về vị trí đầu của richtextbox) 
     TextPointer resetpos = richTextBox.Document.ContentStart; 
     richTextBox.CaretPosition = resetpos; 

     // STEP2: get start Position of your line and get startpos of your line +1 (mean end positon of your need line) (Vietnammes: Lấy vị trí đầu và cuối của line) 
     TextPointer startPos = richTextBox.CaretPosition.GetLineStartPosition(line); 
     TextPointer endPos = richTextBox.CaretPosition.GetLineStartPosition(line + 1); 

     // STEP3: return if Error 
     if (startPos == null) return; 
     if (endPos == null) return; 

     // STEP4: Clear properties of your previous line (i'm highlighting line by line of richtextbox, so i need to clear properties of previous line before apply new properties to next line) 
// Xóa các thuộc tính áp dụng cho dòng trước, vì tôi bôi đen từng dòng trong richtextbox nên khi bôi đen dòng này tôi sẽ bỏ bôi đen dòng trước kia đi 
     if (line != 0) // in this case, i clear properties when line != 0, ofcoursce you can change it (trong trường hợp dòng 0, tôi không xóa dòng trước vì trước nó không có dòng nào cả) 
     { 
      Mytextrange2.ClearAllProperties(); 
      //Mytextrange2.ApplyPropertyValue(TextElement.BackgroundProperty,Brushes.DarkGray); 
      Mytextrange2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.DarkGray); 
     } 

     // STEP5: Select new textrang and apply new properties to your new line // Dùng textrange để chọn dòng cần bôi đen, sau đó add các thuộc tính vào 
     Mytextrange2.Select(startPos, endPos); // select range of text to apply new properties 
     Mytextrange2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold); 
     Mytextrange2.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.DarkGray); 
     Mytextrange2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black); 

     // STEP6: scroll richtextbox to next 14th line to make reasonable view (if imposible). // scroll đến 14 dòng sau dòng được chọn, để dòng được chọn ở giữa khung màn hình, bạn có thể chọn dòng khác 
     richTextBox.CaretPosition = startPos; // Set CaretPosition to selected line 
     startPos = richTextBox.CaretPosition.GetLineStartPosition(14); //(find position of next 14th line to scroll) Change value 14 to have more reasonable view 
     if (startPos != null) richTextBox.CaretPosition = startPos; // Set caretposition to position of next 14 lines 
     richTextBox.Focus(); // scroll richtextbox to caretposition 
    } 
    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     // Mytextrange2 là biến toàn cục muốn dùng để thực hiện xóa properties của dòng trước, nên tôi phải khởi tạo ở 1 chỗ khác ngoài hàm Selectline 
// Initialize Mytextrang2 
     Mytextrange2 = new TextRange(richTextBox.Document.ContentStart,richTextBox.Document.ContentEnd); 
    }