在 RichEditBox 中突出显示单词

Highlighting words in RichEditBox

需要用五种颜色高亮文档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 中,一个空行 returns 并且相应地,颜色没有改变。我无法确定错误的原因。

您发布的代码未设置选择,因此 myRichEdit.Document.Selection 为空。您可以使用 ITextRange.SetRange to set the selection. And you can use 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;
        }
    }
}