我一直在尝试编写一个程序来在 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”着色,但第二个“go”不会着色)。
我估计出现这种情况是因为textRange工作不正常,或者TextPointer出了问题。此外,index 和 endIndex 是正确的 - 我已经测试过它们。
我感谢您的帮助。
试试这个代码:
TextRange rangeText = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeText.Text = "Text1 ";
rangeText.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeText.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
TextRange rangeWord = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeWord.Text = "word ";
rangeWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
rangeWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);
TextRange rangeTextOne = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeTextOne.Text = "Text2 ";
rangeTextOne.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeTextOne.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)