2016-02-25 110 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; 
     } 
    } 
}