【问题标题】:Highlight special word in a TextBox突出显示文本框中的特殊单词
【发布时间】:2011-11-15 08:28:27
【问题描述】:

如何突出显示文本中出现的所有单词列表。 例如,我确实有一个字符串列表(“if”、“else”、“then”、“while”、“true”)。 我确实需要在 TextBox 中找到它们并突出显示它们(前景色 + 背景色)。

外观示例:

目前的做法是覆盖 TextBox 并在 OnTextChange 事件中做“某事”。

【问题讨论】:

  • 对于更高级的格式,我最终选择了 FlowDocument 和 FlowDocumentReader。不同的语法,但我发现标记 FlowDocument 更合乎逻辑。您必须解析单词然后标记单词。如果您想保留文本,请考虑使用 RichTextBox。当您在 RichTextBox 中标记位置(与 FlowDocument 源相反)时,模型会有所不同。缺点是 FlowDocument 很复杂。

标签: wpf syntax textbox highlight


【解决方案1】:
【解决方案2】:

我实际上正在使用一些使用 RichTextBox 的方法,但我的步骤很慢。 意识到我如何标记事物仍然存在一些错误。例如,一切都得到 在要标记的第一个字符之后标记。所以它看起来就像这样:

pos is the position of the character i want to mark (+1 for just one character), in OnTextChange
MarkForeground(pos + 2, pos + 2 + 1, Colors.Green); // +2 for some awkward wpf bug probably ;)

private void MarkForeground(int start, int end, Color col)
    {
        TextPointer startPointer = this.Document.ContentStart.GetPositionAtOffset(start);
        TextPointer endPointer = this.Document.ContentStart.GetPositionAtOffset(end);

        if (startPointer != null && endPointer != null)
        {

            TextRange range = new TextRange(startPointer, endPointer);


            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(col));

        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2014-03-08
    • 2013-01-23
    相关资源
    最近更新 更多