I need to make search in some textbox(or some other control) but I cannot find good solution ...
To be more clear I have one text box and when i type text in it,i need to highlight text in other control
.
In winform app I write code for this, and I use RichTextBox
, that was not a big problem.
But in windows store application I not have RichTextBox
, here are RichTextBlock
and RichEditBox
and with this controls i cannot find way to search for text.
Is this even possible? maybe I can use some external library? Please help and Thanx.
You can use TextBox (for inputs) and TextBlock (for highlight content). The TextBox control has an event named TextChanged raised every key pressed. TextBlock has a property named Inlines inside you can put some text element (like Span, Run, etc). Your TextBlock can be declared like this :
<TextBlock x:Name="MyTb">
Lorem ipsum sit amet
</TextBlock>
Your TextBox :
<TextBox TextChanged="TextBox_TextChanged" />
And the TextChanged event :
var txtToHighlight = (sender as TextBox)?.Text;
if (!string.IsNullOrWhiteSpace(txtToHighlight))
{
var tb = MyTb;
var currentTxt = tb.Text;
tb.Inlines.Clear();
var ix = currentTxt.IndexOf(txtToHighlight);
if (ix >= 0)
{
var highlightContent = new Span { Foreground = new SolidColorBrush(Colors.Red) };
highlightContent.Inlines.Add(new Run { Text = currentTxt.Substring(ix, txtToHighlight.Length) });
tb.Inlines.Add(new Run { Text = currentTxt.Substring(0, ix) });
tb.Inlines.Add(highlightContent);
tb.Inlines.Add(new Run { Text = currentTxt.Substring(ix + txtToHighlight.Length) });
}
else
{
tb.Text = currentTxt;
}
}