Highlight all occurrences of selected word in AvalonEdit

早过忘川 提交于 2019-12-10 04:13:21

问题


I need to highlight all occurrences of selected word in AvalonEdit. I created an instance of HihglinghtingRule class:

 var rule = new HighlightingRule()
   {
       Regex = regex, //some regex for finding occurences
       Color = new HighlightingColor {Background = new SimpleHighlightingBrush(Colors.Red)}
   };

What should I do after it ? Thanks.


回答1:


To use that HighlightingRule, you would have to create another instance of the highlighting engine (HighlightingColorizer etc.)

It's easier and more efficient to write a DocumentColorizingTransformer that highlights your word:

public class ColorizeAvalonEdit : DocumentColorizingTransformer
{
    protected override void ColorizeLine(DocumentLine line)
    {
        int lineStartOffset = line.Offset;
        string text = CurrentContext.Document.GetText(line);
        int start = 0;
        int index;
        while ((index = text.IndexOf("AvalonEdit", start)) >= 0) {
            base.ChangeLinePart(
                lineStartOffset + index, // startOffset
                lineStartOffset + index + 10, // endOffset
                (VisualLineElement element) => {
                    // This lambda gets called once for every VisualLineElement
                    // between the specified offsets.
                    Typeface tf = element.TextRunProperties.Typeface;
                    // Replace the typeface with a modified version of
                    // the same typeface
                    element.TextRunProperties.SetTypeface(new Typeface(
                        tf.FontFamily,
                        FontStyles.Italic,
                        FontWeights.Bold,
                        tf.Stretch
                    ));
                });
            start = index + 1; // search for next occurrence
        }
    }
}


来源:https://stackoverflow.com/questions/9223674/highlight-all-occurrences-of-selected-word-in-avalonedit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!