Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Highlighted Text does not scroll correctly

$
0
0

I have a RichTextBox that I am searching.  When the search result is selected the text is then highlighted correctly.  However, once the RichTextBox is scrolled, the highlight does not follow the text that was highlighted, but instead stays where the text was initially found (see attached screenshot). Below is the code that highlights the desired text initially.  Any thoughts on how to get the highlight to follow the text as it is scrolled?

class SearchResult
{
	public string Display { get; set; }
	public TextPointer Start { get; set; }
	public TextPointer End { get; set; }
}

public void DoSearch()
{
	string toSearch = TextBox_Find.Text.Replace(@"\", @"\\")
		.Replace("^", @"\^")
		.Replace("$", @"\$")
		.Replace(".", @"\.")
		.Replace("|", @"\|")
		.Replace("?", @"\?")
		.Replace("*", @"\*")
		.Replace("+", @"\+")
		.Replace("(", @"\(")
		.Replace(")", @"\)")
		.Replace("[", @"\[")
		.Replace("]", @"\]")
		.Replace("{", @"\{")
		.Replace("}", @"\}");
	TextRange range = new TextRange(RichTextBox_AllComments.Document.ContentStart, RichTextBox_AllComments.Document.ContentEnd);
	Regex reg = new Regex(toSearch, RegexOptions.Compiled | RegexOptions.IgnoreCase);

	var start = RichTextBox_AllComments.Document.ContentStart;
	while (start != null && start.CompareTo(RichTextBox_AllComments.Document.ContentEnd) < 0)
	{
		if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
		{
			var matches = reg.Matches(start.GetTextInRun(LogicalDirection.Forward));
			TextRange textrange = null;
			foreach (Match match in matches)
			{
				textrange = new TextRange(start.GetPositionAtOffset(match.Index, LogicalDirection.Forward), start.GetPositionAtOffset(match.Index + match.Length, LogicalDirection.Backward));
				SearchResults.Add(new SearchResult() { Display = "Result " + (SearchResults.Count + 1).ToString(), Start = textrange.Start, End = textrange.End });
			}
			if (textrange != null) start = textrange.End;
		}
		start = start.GetNextContextPosition(LogicalDirection.Forward);
	}
}

private void ListBox_Find_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
	if (e.AddedItems.Count > 0)
	{
		bFindItemSelected = true;
		SearchResult sr = e.AddedItems[0] as SearchResult;
		RichTextBox_AllComments.Focus();
		RichTextBox_AllComments.Selection.Select(sr.Start, sr.End);
		((UIElement)ListBox_Find.ItemContainerGenerator.ContainerFromItem(ListBox_Find.SelectedItem)).Focus();
	}
}


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>