Daniel Little
Daniel Little

Reputation: 17263

Highlight text in Windows 8 TextBox

I'm looking for a way to highlight (not select) words based on search terms inside a Windows.UI.Xaml.Controls.TextBox control.

There doesn't seem to any way to override the text rendering behaviour? Can this be done with the textbox control?

Edit: I was originally trying to use the RichEditBox but was having a problem with being able to paste in formatted text which I was trying to prevent (the only event I can clear the formatting on is TextChanged which seems a little late). I also really need more control over the rendering of the highlights

Upvotes: 2

Views: 1861

Answers (3)

Tommy
Tommy

Reputation: 583

I am having the same issue. But Incase you didn't know, I'll post this anyway (it's not a complete answer but might get you started.)

You can highlight words by using:

int indexOfFoundKeyword = 1;
int lastIndexOfFoundKeyword = 12;
txtbox.SelectionStart = indexOfFoundKeyword;
txtbox.SelectionLength = lastIndexOfFoundKeyword;

If you place this inside a button click event and then type about 20 chars and click the button you'll see that you can highlight words in a Metro textbox. The problem that I'm having is getting the start and ending of the found keyword so that I know what values to assign to SelectionStart and SelectionLength and if I understand your question correctly, I think that's where you're stuck at, too.

Update

OK, this seems to be a little tempremental but works most of the time. (and accurate when it does work):

    // find the word 'jason'.
    string word = "jason";
    int a, b;
    a = genericBox.Text.IndexOf(word);
    b = word.Length;

    genericBox.SelectionStart = a;
    genericBox.SelectionLength = b;

If all you are trying to do is find some text, then select it, then this proves that it can be done. Now I know this is not the best way but it's the only way I've been able to get something like this to work in a plain TextBox for metro apps.

Upvotes: 1

Mamta D
Mamta D

Reputation: 6450

Perhaps you could create a control based on the TextBox control or altogether create a custom control. See here and here for more help.

Upvotes: 0

U1199880
U1199880

Reputation: 905

Textboxes are very limited in regards to formatting and text selection.

You might want to use the RichTextBox control rather than a TextBox as it gives you greater selection and formatting capabilities to make highlighting multiple terms easier.

Here's a quick start: http://www.devx.com/dotnet/Article/34644

Upvotes: 2

Related Questions