我在我的 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);
}
}