WPF RichTextBox Find Extension Method

I needed to be able to find text in a WPF RichTextBox.

I ended up with the following:

public static int Find(this RichTextBox richTextBox, string text, int startIndex = 0)
{
    var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
    richTextBox.Selection.Select(textRange.Start, textRange.Start);     // clear previous select if there was one
 
    textRange.ClearAllProperties();
    var index = textRange.Text.IndexOf(text, startIndex, StringComparison.OrdinalIgnoreCase);
    if (index > -1)
    {
        var textPointerStart = textRange.Start.GetPositionAtOffset(index);
        var textPointerEnd = textRange.Start.GetPositionAtOffset(index + text.Length);
 
        var textRangeSelection = new TextRange(textPointerStart, textPointerEnd);
        textRangeSelection.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
        richTextBox.Selection.Select(textRangeSelection.Start, textRangeSelection.End);
        richTextBox.Focus();
    }
 
    return index;
}

It is used as follows:

var startIndex = 0;     // index to start find at.  Allows for a find next option.
var index = richTextBox1.Find(textBoxFindText.Text, startIndex);

If index < 0 then there was no text found. Extension method is set up as forward only.

Comments are closed.