Search code examples
c#wpftextbox

Automatic highlighting a part of the text in a TextBox or RichTextBox


Is it possible to highlight a part of a text without selecting this part of the text preferably with a different color in Textbox or Rich TextBox? In fact, I mean, a part of the text is highlighted by another color differing from the color assigned for text selection. To clarify, I have attached an image showing this behavior. (The image is from a website, not WPF). The bold and dark green part is a text which is just highlighted, and the gray region is a selected part. enter image description here


Solution

  • Using the RichTextBox element allows for more styling options which, to my knowledge, aren't available for the regular TextBox element.

    Here is an approach that I have created:

    // Generate example content
    FlowDocument doc = new FlowDocument();
    
    Run runStart = new Run("This is an example of ");
    Run runHighlight = new Run("text highlighting in WPF");
    Run runEnd = new Run(" using the RichTextBox element.");
    
    // Apply highlight style
    runHighlight.FontWeight = FontWeights.Bold;
    runHighlight.Background = Brushes.LightGreen;
    
    // Create paragraph
    Paragraph paragraph = new Paragraph();
    paragraph.Inlines.Add(runStart);
    paragraph.Inlines.Add(runHighlight);
    paragraph.Inlines.Add(runEnd);
    
    // Add the paragraph to the FlowDocument
    doc.Blocks.Add(paragraph);
    
    // Apply to RichTextBox
    YourRichTextBoxHere.Document = doc;
    

    View Screenshot