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
Asked
Active
Viewed 3,193 times
1
-
See http://stackoverflow.com/questions/2245928/mvvm-and-the-textboxs-selectedtext-property – ANeves Nov 28 '13 at 15:24
2 Answers
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.
-
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
-
1Actually 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
-
Just want to point out that you can't use double-quotations inside a `{Binding}` as they would be invalid. – erodewald Oct 10 '12 at 15:08
-
Miklós Balogh - you cant do that - it will always give you 0 as CaretIndex is not bindable. – shahar eldad Feb 27 '13 at 15:14
-
Agreed. This always returns zero because every time you lose focus on the textbox it just sets the Caretindex to 0. – James McDuffie Apr 06 '18 at 22:25