2012-08-10 204 views
4

我想實現一些以編程方式更改文本背景時提供了文檔行的東西(與文本塊選擇看起來非常相似的東西)將此用於我設計的IDE的調試斷點)。我不想使用選擇,因爲它會導致文本框滾動。Avalonedit如何以編程方式更改文本的背景

我想我需要使用DocumentColorizingTransformer,但我不是100%確定如何去做這件事。

public class ColorizeAvalonEdit : ICSharpCode.AvalonEdit.Rendering.DocumentColorizingTransformer 
    { 
     protected override void ColorizeLine(ICSharpCode.AvalonEdit.Document.DocumentLine line) 
     { 
      int lineStartOffset = line.Offset; 
      string text = CurrentContext.Document.GetText(line); 
      int start = 0; 
      int index; 
      if (line.LineNumber == LogicSimViewCodeWPFCtrl.currentLine) 
      { 
       while ((index = text.IndexOf(text, start)) >= 0) 
       { 
        base.ChangeLinePart(
         lineStartOffset + index, // startOffset 
         lineStartOffset + index + text.Length, // endOffset 
         (VisualLineElement element) => 
         { 
          element.TextRunProperties.SetBackgroundBrush(Brushes.Red); 

         }); 
        start = index + 1; // search for next occurrence 
       } 
      } 
     } 
    } 

currentLine是將突出顯示的部分。

上面的代碼確實工作正常..唯一的問題是,如果currentLine有變化,而我正在查看該行,它不會突出更新的行,直到我滾動到文檔的另一部分(隱藏更新的行) ,然後回到更新後的行。

另外,如何讓行號從零開始?

回答

2

我找到了答案

TxtEditCodeViewer.TextArea.TextView.Redraw(); 
3

既然是他們的創作,我就偷看了SharpDevelop的來源以及他們是如何做到的。

他們定義了書籤類型(BreakpointBookmark)並將書籤添加到該行。 書籤本身設置CreateMarker方法中的行的顏色。奇怪的是,在SharpDevelop中不能配置斷點的顏色。

希望它有幫助。

protected override ITextMarker CreateMarker(ITextMarkerService markerService) 
    { 
     IDocumentLine line = this.Document.GetLine(this.LineNumber); 
     ITextMarker marker = markerService.Create(line.Offset, line.Length); 
     marker.BackgroundColor = Color.FromRgb(180, 38, 38); 
     marker.ForegroundColor = Colors.White; 
     return marker; 
    } 
+1

欣賞的答案。然而,在看看sharpdevelop如何處理這個問題之後,我認爲不得不添加大量的類,接口來對代碼進行實質性的改變,以實現看似簡單的功能,這聽起來不太可行。 – l46kok 2012-08-17 04:19:21

+0

在內心深處,SharpDevelop和你所做的一樣。它創建斷點作爲TextSegments的書籤標記。在TextMarkerService.ColorizeLine中,它可以找到它自己的標記(分段)並着色整行。你需要創建一個類MyMarker:TextSegment並將其保存在一個類型的變量中。 TextSegmentCollection 。在ColorizeLine中,從TextMarkerService.ColorizeLine複製並完成。 – edokan 2012-08-17 07:48:26

+0

對於行號,您必須編輯LineNumberMargin.OnRender並構建AvalonEdit。 – edokan 2012-08-17 07:53:14

0

這不是一個重複的this question

但是,您應該在編輯器上調用InvalidateArrange()或在每個更改的視覺上調用InvalidateVisual()

+0

我稱之爲。沒有運氣。更具體地說: TxtEditCodeViewer.TextArea.TextView.InvalidateVisual(); TxtEditCodeViewer.TextArea.TextView.InvalidateArrange(); TxtEditCodeViewer.TextArea.TextView.InvalidateMeasure(); – l46kok 2012-08-20 00:55:43

相關問題