[英]Highlight text in RichTextBox
我正在尝试使用RichTextBox和我的第一感觉:“使用它有什么复杂!”
因此,我试图突出显示RichTextBox中包含的文本。
我目前有以下代码:
TextRange range = new TextRange(MyTextInput.Document.ContentStart, MyTextInput.Document.ContentEnd);
range.Text = @"TOP a multiline text or file END";
Regex reg = new Regex("(top|file|end)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
foreach (Match match in reg.Matches(range.Text))
{
TextPointer start = range.Start.GetPositionAtOffset(match.Index, LogicalDirection.Forward);
TextPointer end = range.Start.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward);
// text contains the exact match I want
string text = range.Text.Substring(match.Index, match.Length);
// here the highlighted text isn't the text I searched...
TextRange textrange = new TextRange(start, end);
textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
textrange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
}
TOP
已正确突出显示,但未file
或end
但突出显示了我or
。
有什么建议么?
您必须想象RichTextBox在幕后能做什么才能理解行为。 我不知道,但我想像一下:第1-2 RichTextBox
的内容设置为带有Run
的Paragraph
。
然后使用ApplyPropertyValue
进行第一次迭代,更改RichTextBox的内容! 现在,它包含一个带有Span
(内部带有Run
)和运行的Paragraph
。
然后,您必须考虑正则表达式匹配和GetPositionAtOffset
之间的差异。 正则表达式匹配返回字符串中char位置的索引。
GetPositionAtOffset使用“以符号为单位的偏移量,要计算并返回其位置” ,其中符号为:
- TextElement元素的开始或结束标记。
- InlineUIContainer或BlockUIContainer中包含的UIElement元素。 请注意,这样的UIElement始终被精确地算作一个符号。 UIElement包含的任何其他内容或元素均不算作符号。
- 文本Run元素内的16位Unicode字符。
因此,您可能想做的是这样的事情:
TextRange range = new TextRange(MyTextInput.Document.ContentStart, MyTextInput.Document.ContentEnd);
range.Text = @"TOP a multiline text or file END";
Regex reg = new Regex("(top|file|end)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var start = MyTextInput.Document.ContentStart;
while (start != null && start.CompareTo(MyTextInput.Document.ContentEnd) < 0)
{
if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
var match=reg.Match(start.GetTextInRun(LogicalDirection.Forward));
var textrange = new TextRange(start.GetPositionAtOffset(match.Index, LogicalDirection.Forward), start.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward));
textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
textrange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
start= textrange.End; // I'm not sure if this is correct or skips ahead too far, try it out!!!
}
start = start.GetNextContextPosition(LogicalDirection.Forward);
}
*免责声明:我现在还没有尝试过,因为我离开发环境还很遥远。 我什至不知道它是否可以编译,但我希望如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.