2016-02-25 109 views
2

需要在文档RichEditBox中以5n颜色突出显示一个子字符串。为此我写了一个方法:在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中返回一个空行,相应地,颜色不会改变。我无法确定错误的原因。

回答

3

您发布的代码没有设置选择,因此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; 
     } 
    } 
}