1

I want a button to insert text that is selected in a listbox to a textbox. I am trying to use command for this, I will pass the current caret index as command parameter, then the Command handler will insert the selected text at this index. Is it possible? I don't know how to refer to aTextBox.CaretIndex in a xaml

Louis Rhys
  • 34,517
  • 56
  • 153
  • 221

2 Answers2

3

This problem is similar to this question.

The point is that it is no use to bind the property CaretIndex since it is not a DependencyProperty, as you do not get notifications of value changes. Specifically, if you bind directly to CaretIndex the program will compile but the value of CaretIndex from the data binding will always be 0, even if you move the cursor in the textbox.

You can instead create an attached property that you could bind instead of CaretIndex. A solution for that is proposed here where an attached property is added in order to bind the SelectedText property, which is also not a dependency property. The idea is the same.

Community
  • 1
  • 1
Klaus78
  • 11,648
  • 5
  • 32
  • 28
  • In this case it doesn't matter because he wants to use the CaretIndex as the **source** of the binding. It could be a CLR. But it would be wrong if he would want to use this prop as a **target** of the binding – Miklós Balogh Oct 10 '12 at 12:25
  • 1
    Actually you can set CaretIndex as source of binding but there is no notification when its values changes. As a result the command parameter is always 0 – Klaus78 Oct 10 '12 at 12:37
0

You can bind to the TextBox by name and giving the CaretIndex to the Path prop

<TextBox Name="MyTextBox" Text="My Text" />
<Button Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=MyTextBox Path=CaretIndex}"/>
Miklós Balogh
  • 2,164
  • 2
  • 19
  • 26