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);
}
}