令人难以置信的AvalonEdit WPF TextEditor控件似乎缺少一项重要功能,或者至少我无法弄清楚。 给定偏移量和长度,使用HighlightColor 突出显示TextDocument中的该部分。简单吧?

显然不是。我有RTFM,有关“语法突出显示”的文档更让我感到困惑。 Someone else asked the same question in the SharpDevelop forums,恐怕我无法理解格伦沃尔德先生的回答。

这是我尝试使用DocumentHighlighter类的方法(当然这是行不通的):

    textEditor1.Text = "1234567890";

    HighlightingColor c = new HighlightingColor() { FontWeight = FontWeights.ExtraBold };

    DocumentHighlighter dh = new DocumentHighlighter(textEditor1.Document, new HighlightingRuleSet());
    HighlightedLine hl = dh.HighlightLine(1);

    hl.Sections.Add(new HighlightedSection() { Color = c, Offset = 1, Length = 3 });

谢谢你的帮忙!

最佳答案

您是否在this article中看到了此内容-似乎正是您要的内容:

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
}   }   }

它以粗体突出显示单词AvalonEdit。

10-01 17:18