0

Anyone has any idea how to highlight in a textblock?

Basically i have 2 textblock and both have the same string. When I highlight part of the string in one of the textblock, the other textblock shows the same highlighted part as well. I am basically stuck at how to do the highlighting.

Thanks in advance

kkh
  • 4,799
  • 13
  • 45
  • 73

1 Answers1

0

Do you have a TextBlock or a TextBox? I'm going to assume it's a TextBox, since TextBlock does not support text selection.

In that case, you can simply use data binding to keep this in sync.

<TextBox Name="text1" />
<TextBox Name="text2" 
       SelectionStart="{Binding Path=SelectionStart, ElementName=text1}" 
       SelectionLength="{Binding Path=SelectionLength, ElementName=text1}" />

This should ensure that the same area of text is selected in text2 when the user selects it in text1 and vice-versa.

EDIT See this answer for instructions on how to bind to these properties.

If you create a custom TextBox as described in the linked answer, your code would look something like this:

<SelectionBindingTextBox Name="text1" />
<SelectionBindingTextBox Name="text2" 
       BindableSelectionStart="{Binding Path=BindableSelectionStart, ElementName=text1}" 
       BindableSelectionLength="{Binding Path=BindableSelectionLength, ElementName=text1}" />
Community
  • 1
  • 1
Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
  • Oh i tried but I have this error A 'Binding' cannot be set on the 'SelectionStart' property of type 'TextBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject. – kkh Oct 24 '11 at 06:00
  • i use a textbox as suggested. just realised textblock cannot select text – kkh Oct 24 '11 at 06:02
  • hmm nope i still have the dependency error. I read somewhere that textbox cannot support selection dependency? – kkh Oct 24 '11 at 16:14
  • hmm i still get the same error. Is there any thing i need to set or define? – kkh Oct 25 '11 at 03:11
  • @user992618: You'll have to use your custom `TextBox` type instead of `TextBox` in order to do this. – Adam Robinson Oct 25 '11 at 03:17
  • Is there any online examples that illustrate how it is used. I am totally confused? my xaml is as below and my textbox will just follow the example as given above? – kkh Oct 25 '11 at 04:55