Highlighting words in RichEditBox

梦想与她 提交于 2020-01-02 08:54:46

问题


It is needed to highlight by fiven colour a substring in the document RichEditBox. For this purpose I wrote a method:

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

In the debugger you can see that there is a substring and isFinded is equal with the number of signs (or symbols) in the found substring. It means the fragment is found and judging by the description of the method FindText should be highlighted but it isn't. In textStr2 an empty line returns and, correspondingly, the colour doesn't change. I cannot identify the reasons of the error.


回答1:


The code you postted did not set the selection, so the myRichEdit.Document.Selection is null. You can use ITextRange.SetRange to set the selection. And you can use ITextRange.FindText method to find the string in the selection.

For example:

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


来源:https://stackoverflow.com/questions/35634345/highlighting-words-in-richeditbox

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