需要将文档 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 中返回一个空行,相应地,颜色不会改变。我无法确定错误的原因。