AvalonEdit WPF TextEditor (SharpDevelop): How to highlight a specific range of text?

后端 未结 4 948
温柔的废话
温柔的废话 2020-12-30 14:24

The incredibly awesome AvalonEdit WPF TextEditor control seems to lack an important feature, or at least i can\'t figure it out. Given an offset and a length, highli

4条回答
  •  余生分开走
    2020-12-30 15:00

    You need to create a custom ColorizingTransformer to do that. The above example is actually highlighting a specific word. Still, you can change it a little bit to to colorize or highlight a portion.

    I used Avalon TextEditor for my Console+ project (which is in a very primitive stage at the moment)

    public class OffsetColorizer : DocumentColorizingTransformer
    {
        public int StartOffset { get; set; }
        public int EndOffset { get; set; }
    
        protected override void ColorizeLine(DocumentLine line)
        {
            if (line.Length == 0)
                return;
    
            if (line.Offset < StartOffset || line.Offset > EndOffset)
                return;
    
            int start = line.Offset > StartOffset ? line.Offset : StartOffset;
            int end = EndOffset > line.EndOffset ? line.EndOffset : EndOffset;
    
            ChangeLinePart(start, end, element => element.TextRunProperties.SetForegroundBrush(Brushes.Red));
        }
    }
    

    And you can add the colorizer to the editor by adding it to LineTransformers collection.

    tbxConsole.TextArea.TextView.LineTransformers.Add(_offsetColorizer);
    

提交回复
热议问题