在 RichEditBox 中突出显示单词

ska*_*rik 3 c# win-universal-app

需要将文档 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;
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

在调试器中,您可以看到有一个子字符串,并且 isFinded 与找到的子字符串中符号(或符号)的数量相等。这意味着找到了片段,根据方法 FindText 的描述判断应该突出显示,但事实并非如此。在 textStr2 中返回一个空行,相应地,颜色不会改变。我无法确定错误的原因。

Jay*_*den 5

您发布的代码未设置选择,因此 myRichEdit.Document.Selection为空。您可以使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)