private void Search_Click(object sender, RoutedEventArgs e)//查询定位文本{ ListtextRanges = FindWordFromPosition(richTextBox1.Document.ContentStart, txtSearch.Text); foreach (var range in textRanges) { range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Red)); //range.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold); //range.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.PowderBlue)); }}
ListFindWordFromPosition(TextPointer position, string word){ List matchingText = new List (); while (position != null) { if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) { //带有内容的文本 string textRun = position.GetTextInRun(LogicalDirection.Forward); //查找关键字在这文本中的位置 int indexInRun = textRun.IndexOf(word); int indexHistory = 0; while (indexInRun >= 0) { TextPointer start = position.GetPositionAtOffset(indexInRun + indexHistory); TextPointer end = start.GetPositionAtOffset(word.Length); matchingText.Add(new TextRange(start, end)); indexHistory = indexHistory + indexInRun + word.Length; textRun = textRun.Substring(indexInRun + word.Length);//去掉已经采集过的内容 indexInRun = textRun.IndexOf(word);//重新判断新的字符串是否还有关键字 } } position = position.GetNextContextPosition(LogicalDirection.Forward); } return matchingText;}