Good day!
I am trying to make simple editor of code, so I want to be able to select the text line and change it color to red, using ICSharpCode.AvalonEdit.TextEditor
.
But I do not know how to use it. Can you help me to change color of text line?
Thank you!
To select a line, use the Select() method:
var line = editor.Document.GetLineByOffset(lineOffset);
editor.Select(line.Offset, line.Length);
Changing the color of a line programatically is tricky tho, as AvalonEdit is a code editor, not a rich text editor, the coloring is mostly used for syntax highlighting. According to this post from the SharpDevelop forums, you should create a DocumentColorizingTransformer. Their example should work for you (I removed all error checking code for better readability):
class LineColorizer : DocumentColorizingTransformer
{
int lineNumber;
public LineColorizer(int lineNumber)
{
this.lineNumber = lineNumber;
}
protected override void ColorizeLine(ICSharpCode.AvalonEdit.Document.DocumentLine line)
{
if (!line.IsDeleted && line.LineNumber == lineNumber) {
ChangeLinePart(line.Offset, line.EndOffset, ApplyChanges);
}
}
void ApplyChanges(VisualLineElement element)
{
// This is where you do anything with the line
element.TextRunProperties.SetForegroundBrush(Brushes.Red);
}
}
Then, to apply it for your document, you can use it as follows:
editor.TextArea.TextView.LineTransformers.Add(new LineColorizer(lineOffset));