我一直在尝试编写一个程序来搜索richTextBox 中的单词。我已经做了大部分,但看起来我错过了一些东西。我想为找到的单词着色,所以我写了以下内容:
private void button1_Click(object sender, RoutedEventArgs e)
{
richTextBox1.SelectAll();
string words = richTextBox1.Selection.Text; // to get the the whole text
int length = words.Length; // length of text
string search = textBox1.Text; // the word being searched for
int search_length = search.Length;
int index =0; // to go through the text
int endIndex = 0; // the end of the got word
// pointer to the begining and the ending of the word which will be colored.
TextPointer start_pointer, end_pointer;
if(length>0 &&search_length>0) // text exists
while(index<length-search_length)
{
index = words.IndexOf(search, index);
if (index < 0) // not found
break;
endIndex = index+search.Length-1; // last char in the word
start_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(index, LogicalDirection.Forward);
end_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(endIndex + 1, LogicalDirection.Forward);
TextRange got = new TextRange(start_pointer, end_pointer);
//just for debugging
MessageBox.Show("start =" + index + " end =" + endIndex + " " + got.Text);
got.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
index =endIndex+1;
}
第一个词是彩色的。但接下来的单词不是(即如果文本是“去上学,我会去市场”,要搜索“去”这个词,然后我按下搜索按钮,结果会为第一个“go”着色,但第二个不会着色)。
我估计这是因为 textRange 工作不正常,或者 TextPointer 出了问题。此外, index 和 endIndex 是正确的 - 我已经测试过它们。
我感谢您的帮助。