I have a UWP Desktop application that has a TextBlock control with a very long text. The application has a search option, where the user types a word and the application must select the first occurrence of the word in the text. In a TextBox it is very easy, because the Select method takes two integers as parameters. But in the Select method of the TextBlock the parameters are TextPointers. How do I make this selection?
You could add a TextHighlighter
with TextRange
s to the TextHighlighters
of the TextBlock
, e.g.:
var wordToSelect = "long";
var index = tb.Text.IndexOf(wordToSelect);
if (index > -1)
{
var textRange = new TextRange() { StartIndex = index, Length = wordToSelect.Length };
var textHighlighter = new TextHighlighter();
textHighlighter.Ranges.Add(textRange);
tb.TextHighlighters.Add(textHighlighter);
}
XAML:
<TextBlock x:Name="tb" Text="some long text" />