[英]TextRange and RichTextBox in C# WPF
我一直在尝试编写一个程序来搜索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是正确的-我已经测试了它们。
我感谢您的帮助。
试试这个代码:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.