【发布时间】:2015-09-08 16:34:08
【问题描述】:
我在 WPF (4.0) 中使用 RichTextBox,并使用 GetPositionAtOffset() 方法获取 RichTextBox 内容中两个位置之间的文本范围。
1) 我从 MyRichTextBox.Document.ContentStart 初始化文本指针“位置”:
TextPointer position = RTBEditor.Document.ContentStart;
2) 我像这样从我的 RichTextBox 中获取文本:
var textRun = new TextRange(RTBEditor.Document.ContentStart, RTBEditor.Document.ContentEnd).Text;
3) 使用 Regex,我在 textRun 中找到我想要的字符串,并获取开始的索引和结束的索引(我在“/*”和“*/”之间搜索文本):
Regex regex = new Regex(@"/\*([^\*/])*\*/");
var match = regex.Match(textRun);
TextPointer start = position.GetPositionAtOffset(matchBegin.Index, LogicalDirection.Forward);
TextPointer end = position.GetPositionAtOffset(matchBegin.Index + matchBegin.Length, LogicalDirection.Backward);
但是,当我在文本范围中使用这些指针并对其中的文本进行着色时,在我的 RichTextBox 中着色的不是正则表达式(带有商品索引)中匹配的好文本。
为什么 GetPositionAtOffset() 方法没有给出指定索引处的位置?是这个方法的问题还是其他地方的问题?
谢谢你的回复,我的发展停滞了。
【问题讨论】:
-
删除
RichTextBox并使用适当的代码编辑器,例如AvalonEdit。 -
感谢您的回复。我必须做我自己的代码编辑器(带有richtextbox),我不能使用另一个。如果有人可以向我解释为什么 GetPositionAtOffset() 不起作用并且不给我良好的开始和结束位置,那对我来说很好,我可以继续。
标签: regex wpf richtextbox textrange