问题
i want to color the matched text of a file. first,i load the file text into FileItem.Content ,then use regex to get the matches,and next put the Content into a richtextbox and use the matches to set the caret position and color the text . and the code to fill richtextbox
RtbCodes.Document.Blocks.Clear();
RtbCodes.Document.Blocks.Add(new Paragraph(new Run(item.Content)));
foreach (Match m in item.Matches)
{
TextPointer start1 = RtbCodes.Document.ContentStart.GetPositionAtOffset(m.Index, LogicalDirection.Forward);
TextPointer end = RtbCodes.Document.ContentStart.GetPositionAtOffset(m.Index + m.Length, LogicalDirection.Backward);
if (start1 != null && end != null)
{
RtbCodes.Selection.Select(start1, end);
RtbCodes.Selection.ApplyPropertyValue(Run.BackgroundProperty, "red");
}
}
my problem is the caret selection is not correct at all. see the picture bellow. my regex expression is [\$#]{[.a-zA-Z\d]+} ,so it will get #{blacklist.model1} , but it not.
so ,what's wrong with richtextbox ?
回答1:
You are counting in the invisible "ElementStart" symbols at the beginning of the document, that's why the offset of the selection is incorrect.
To get the correct position, you can count from the beginning of the Run
element.
var newRun = new Run(item.Content);
RtbCodes.Document.Blocks.Add(new Paragraph(newRun));
TextPointer start1 = newRun.ContentStart.GetPositionAtOffset(m.Index, LogicalDirection.Forward);
TextPointer end = newRun.ContentStart.GetPositionAtOffset(m.Index + m.Length, LogicalDirection.Backward);
来源:https://stackoverflow.com/questions/50959130/wpf-richtextbox-selection-with-regex