Zsolt
Zsolt

Reputation: 3283

Highlighting text in a textbox without using RichTextBox control

I have a WPF textbox (not a RichTextBox) and inside this textbox, I want to highlight search results (like in web browsers)

For example if I search for "abc", all occurences of "abc" should be highlighted (for example, with some red background or font)

I want to know if this is possible without using RichTextBox control, or not really?

Upvotes: 1

Views: 1263

Answers (2)

Adriano Repetti
Adriano Repetti

Reputation: 67090

It's possible but it's much more easy to use a RichTextBox so you may consider to use that instead, moreover you cannot change font size but only color (background and/or foreground) and effects.

First you have to derive your own class from TextBox because you'll override its render method. Now override the OnRender() method, here you'll use the DrawingContext.DrawText() method to draw the text (place everything inside a FormattedText object, primary you'll have to adjust its properties to make it similar to a standard TextBox).

Now what you have is a plain TextBox where in addition you draw your text. From this starting point you can choose to:

  • Completely override TextBox text drawing: set TextBox.Foreground property to Brushes.Transparent. User will interact with "real" text but he'll see the text your draw. Please note that to make this works you have to mimic exactly how text is drawn (if you change font size, for example, then they'll be unaligned) in the original TextBox.

  • Add the highlight feature you need keeping the base TextBox text drawing: calculate where the text you want to highlight is and then draw the proper background.

References
This (simplified!) algorithm comes from CodeBox2, it was originally designed to extend a TextBox with some simple editor-like features.

Upvotes: 2

Emond
Emond

Reputation: 50672

There is no built-in functionality for this. Also, the TextBox only supports a single fontstyle for the entire text.

If the text should be read-only, you could use a flow or fixed document and format the text in Run Elements.

Upvotes: 0

Related Questions