突出显示AvalonEdit中所有选定单词的出现位置

Yur*_*kov 7 c# wpf highlighting textedit avalonedit

我需要在AvalonEdit中突出显示所有选定单词.我创建了一个HihglinghtingRule类的实例:

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

我该怎么办?谢谢.

Dan*_*iel 7

要使用它HighlightingRule,您必须创建突出显示引擎的另一个实例(HighlightingColorizer等)

写一个DocumentColorizingTransformer突出你的单词更简单,更有效:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)