wpf richtextbox selection with regex

你离开我真会死。 提交于 2021-01-29 08:37:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!