WPF RichTextBox ApplyPropertyValue

本文关键字:ApplyPropertyValue RichTextBox WPF | 更新日期: 2023-09-27 18:34:01

我在我的WPF富文本框中突出显示了所有不间断空格的出现。找到所需的文本范围后,我调用:

textrange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.DarkRed);

而且它工作正常。但是,如果突出显示发生在文档末尾,则所有新键入的文本也会突出显示,这很糟糕。有没有人知道如何解决这个问题?

完整代码:

private void HighLightNonbreakSpace()
    {
        var start = this.Document.ContentStart;
        char nonBreakSpace = System.Convert.ToChar(160);
        while (start != null && start.CompareTo(this.Document.ContentEnd) < 0)
        {
            if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
            {
                var match = start.GetTextInRun(LogicalDirection.Forward).IndexOf(nonBreakSpace);
                if (match >=0)
                {
                    var matchPos = start.GetPositionAtOffset(match, LogicalDirection.Forward);
                    var textrange = new TextRange(matchPos, matchPos.GetPositionAtOffset(1,LogicalDirection.Forward));
                    textrange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.DarkRed);
                    start = textrange.End;
                }
            }
            start = start.GetNextContextPosition(LogicalDirection.Forward);
        }
    }

WPF RichTextBox ApplyPropertyValue

您可能不仅要突出显示 nbsps,还要取消突出显示其他所有内容,即在您的例程中添加一个 else 分支。默认情况下,新键入的文本将从它之前的任何内容中获取其属性,因此您必须找出最后一个键入的字符是否为 nbsp 并相应地设置其属性。

相关文章:
  • 没有找到相关文章