c# - AvalonEdit WPF 文本编辑器 (SharpDevelop) : How to highlight a specific range of text?

标签 c# .net wpf sharpdevelop avalonedit

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

显然不是。我有 RTFM,关于“语法高亮”的文档让我更加困惑。 Someone else asked the same question in the SharpDevelop forums,恐怕我无法理解 Herr Grunwald 的回答。

这是我的尝试,使用 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。

关于c# - AvalonEdit WPF 文本编辑器 (SharpDevelop) : How to highlight a specific range of text?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5029724/

相关文章:

c# - WPF DataGrid ItemsSource 绑定(bind)到 ObservableCollection 不会更新超出第一个设置?

c# - 如何找到 PowerShell 静态类和方法?

c# - 将 Func<T, int> 值插入 linq-2-sql 查询

调整具有大量控件的窗口大小时的 WPF 性能问题

c# - 当我在 C# 中为 Visual Studio 2017 调用方法时,是否有显式命名参数的快捷方式?

c# - 如何为角色和特定用户使用自定义授权属性?

c# - 如何以增量方式调整 WPF 窗口的大小?

c# - 从在线 SQL Server 获取数据时卡住应用程序

c# - 使用 C# 和 .net 3.5 阅读 RSS 的问题

c# - 有没有一种方法可以只将一个整数传递给我的 View 而无需在 mvc 中创建模型