1

A Windows Phone Question C#

I have a TextBox named "Search" and another TextBox named "Content". If the user adds text into the "Content" TextBox, is there a way, using the "Search" TextBox to search what the user typed in the "Content" TextBox and highlight that specific text?

e.g. When the user wants to search an app from the App List of the phone, It highlights and shows that particular app or any app containing that text.

enter image description here

If anyone has a solution please let me know :)

Samkit Jain
  • 2,523
  • 16
  • 33
Ahmed.C
  • 487
  • 1
  • 6
  • 17

1 Answers1

2

To select text in a TextBox, this question provides the answer, basically:

//To select all text
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

There's only a bit more logic to apply to achieve what you want. First get the input from the Content textbox and find the index of this value in the text in the Search textbox. If the value exists (thus the index being greater than -1), you can set the SelectionStart and SelectionLength.

string content = Content.Text;
int index = Search.Text.IndexOf(content);

if(index > -1)
{
    Search.SelectionStart = index;
    Search.SelectionLength = content.Length;
}

Update:

I tried following code in a WPF solution and it worked so normally this should work too for Windows Phone.

  • SearchTextBox is a TextBox
  • Content is a TextBlock

Just that you know what everything is in the code:

var regex = new Regex("(" + SearchTextBox.Text + ")", RegexOptions.IgnoreCase);

if (SearchTextBox.Text.Length == 0)
{
    string str = Content.Text;
    Content.Inlines.Clear();
    Content.Inlines.Add(str);
}
else
{
    //get all the words from the 'content'
    string[] substrings = regex.Split(Content.Text);
    Content.Inlines.Clear();

    foreach (var item in substrings)
    {
        //if a word from the content matches the search-term
        if (regex.Match(item).Success)
        {
            //create a 'Run' and add it to the TextBlock
            Run run = new Run(item);
            run.Foreground = Brushes.Red;
            Content.Inlines.Add(run);
        }
        else //if no match, just add the text again
            Content.Inlines.Add(item);
    }
}
Community
  • 1
  • 1
Abbas
  • 14,186
  • 6
  • 41
  • 72
  • Hey Abbas, thanks for that but I cant seem to get it working. I tried adding it on a button click event and nothing really happens, even tried adding a focus() method to focus the textbox and then do its selection but still didn't work. Any idea? – Ahmed.C Jan 30 '14 at 00:56
  • Please check my edited answer for another approach. :) – Abbas Jan 30 '14 at 11:49
  • Thank you! I got it from here. – Ahmed.C Jan 31 '14 at 03:25