wpf 用正则表达式选择富文本框 [英] wpf richtextbox selection with regex

查看:52
本文介绍了wpf 用正则表达式选择富文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为文件的匹配文本着色.首先,我将文件文本加载到 FileItem.Content 中,然后使用正则表达式获取匹配项,然后将 Content 放入富文本框并使用匹配项设置插入符号定位文本并为其着色.以及填充richtextbox的代码

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");
        }

    }

我的问题是插入符号选择根本不正确.见下图.我的正则表达式是 [\$#]{[.a-zA-Z\d]+} ,所以它会得到 #{blacklist.model1} ,但它不是.

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.

那么,richtextbox 有什么问题?

so ,what's wrong with richtextbox ?

推荐答案

你在文档开头的不可见的ElementStart"符号中计数,这就是为什么选择的偏移量不正确.

You are counting in the invisible "ElementStart" symbols at the beginning of the document, that's why the offset of the selection is incorrect.

要得到正确的位置,可以从Run元素的开头开始计数.

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);

这篇关于wpf 用正则表达式选择富文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆