【问题标题】:WPF RichTextBox ApplyPropertyValueWPF RichTextBox ApplyPropertyValue
【发布时间】:2012-05-15 03:05:45
【问题描述】:

我在我的 WPF Richtextbox 中突出显示所有出现的不间断空格。 一旦我找到所需的文本范围,我就会调用:

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

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-09-29
      • 2010-09-25
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 2013-11-04
      相关资源
      最近更新 更多