Here are the steps:
Step 1: Open a blank app and add two TextBlocks and a button either from the toolbox or by copying the following XAML code into your grid.
- <StackPanel Margin="10,40,0,0">
- <TextBlock Text="Type the word to find" ></TextBlock>
- <TextBox Name="textToFind" Width="200" Margin="0,10,0,0" HorizontalAlignment="Left"></TextBox>
- <TextBlock Text="Type or Copy and Paste a sentence to find from " Margin="0,10,0,0" ></TextBlock>
- <TextBox Name="sentence" Height="100" Width="300" HorizontalAlignment="Left" Margin="0,10,0,0" TextWrapping="Wrap"></TextBox>
- <Button Name="find" Content="Find" Height="40" Width="120" Click="find_Click" Margin="0,10,0,0" ></Button>
- <TextBlock Name="result" TextWrapping="Wrap" Width="300" HorizontalAlignment="Left"></TextBlock>
- </StackPanel>

Step 2: Add the following namespaces to your project which is needed in further C# code.
- using System.Collections.Generic;
- using Windows.Data.Text;
- using Windows.UI.Text;
- using Windows.UI.Xaml.Documents;
Step 3: Copy and paste the following code to the cs page which will be called on button click event and the corresponding text will be highlighted.
- private void find_Click(object sender, RoutedEventArgs e)
- {
- result.Text = "";
- var mySemanticTextQuery = new Windows.Data.Text.SemanticTextQuery(textToFind.Text);
- IReadOnlyList<Windows.Data.Text.TextSegment> ranges = mySemanticTextQuery.Find(sentence.Text);
- HighlightRanges(result, sentence.Text, ranges);
- }
- public void HighlightRanges(TextBlock tb, String TextContent, IReadOnlyList<TextSegment> ranges)
- {
- int currentPosition = 0;
- foreach (var range in ranges)
- {
- if (range.StartPosition > currentPosition)
- {
- int length = (int)range.StartPosition - currentPosition;
- var subString = TextContent.Substring(currentPosition, length);
- tb.Inlines.Add(new Run() { Text = subString });
- currentPosition += length;
- }
- var boldString = TextContent.Substring((int)range.StartPosition, (int)range.Length);
- tb.Inlines.Add(new Run() { Text = boldString, FontWeight = FontWeights.Bold });
- currentPosition += (int)range.Length;
- }
- if (currentPosition < TextContent.Length)
- {
- var subString = TextContent.Substring(currentPosition);
- tb.Inlines.Add(new Run() { Text = subString });
- }
- tb.Inlines.Add(new Run() { Text = "\r\n" });
- }
Step 4: Run your application and test yourself.


Santhakumar MunuswamyPosted Jan 21, 2016, 2:58 PM
Thanks for nice share