ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

突出显示RichEditBox中的单词

2019-10-27 09:06:22  阅读:159  来源: 互联网

标签:win-universal-app c


需要通过在文档RichEditBox中的子字符串上加高颜色来突出显示.为此,我编写了一个方法:

private async Task ChangeTextColor(string text, Color color)
{
    string textStr;
    bool theEnd = false;
    int startTextPos = 0;
    myRichEdit.Document.GetText(TextGetOptions.None, out textStr);

    while (theEnd == false)
    {
        myRichEdit.Document.GetRange(startTextPos, textStr.Length).GetText(TextGetOptions.None, out textStr);
        var isFinded = myRichEdit.Document.GetRange(startTextPos, textStr.Length).FindText(text, textStr.Length, FindOptions.None);

        if (isFinded != 0)
        {
            string textStr2;
            textStr2 = myRichEdit.Document.Selection.Text;

            var dialog = new MessageDialog(textStr2);
            await dialog.ShowAsync();

            myRichEdit.Document.Selection.CharacterFormat.BackgroundColor = color;
            startTextPos = myRichEdit.Document.Selection.EndPosition;
            myRichEdit.Document.ApplyDisplayUpdates();
        }
        else
        {
            theEnd = true;
        }
    } 
}

在调试器中,您可以看到有一个子字符串,并且isFinded与找到的子字符串中的符号(或符号)数量相等.这意味着该片段已找到,并且通过对FindText方法的描述进行判断应该突出显示,但不是.在textStr2中,返回空行,并且相应地,颜色不变.我无法确定错误原因.

解决方法:

您发布的代码未设置选择,因此myRichEdit.Document.Selection为null.您可以使用ITextRange.SetRange设置选择.您可以使用ITextRange.FindText method在选择中找到字符串.

例如:

private void ChangeTextColor(string text, Color color)
{
    string textStr;

    myRichEdit.Document.GetText(TextGetOptions.None, out textStr);

    var myRichEditLength = textStr.Length;

    myRichEdit.Document.Selection.SetRange(0, myRichEditLength);
    int i = 1;
    while (i > 0)
    {
        i = myRichEdit.Document.Selection.FindText(text, myRichEditLength, FindOptions.Case);

        ITextSelection selectedText = myRichEdit.Document.Selection;
        if (selectedText != null)
        {
            selectedText.CharacterFormat.BackgroundColor = color;
        }
    }
}

标签:win-universal-app,c
来源: https://codeday.me/bug/20191027/1943406.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有