I had a cursorposition property in my viewmodel that decides the position of cursor in textbox on the view. How can i bind the cursorposition property to actual position of the cursor inside the textbox.
Asked
Active
Viewed 2,274 times
2 Answers
1
I'm afraid you can't... at least, not directly, since there is no "CursorPosition" property on the TextBox control.
You could work around that issue by creating a DependencyProperty in code-behind, bound to the ViewModel, and handling the cursor position manually. Here is an example :
/// <summary>
/// Interaction logic for TestCaret.xaml
/// </summary>
public partial class TestCaret : Window
{
public TestCaret()
{
InitializeComponent();
Binding bnd = new Binding("CursorPosition");
bnd.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(this, CursorPositionProperty, bnd);
this.DataContext = new TestCaretViewModel();
}
public int CursorPosition
{
get { return (int)GetValue(CursorPositionProperty); }
set { SetValue(CursorPositionProperty, value); }
}
// Using a DependencyProperty as the backing store for CursorPosition. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CursorPositionProperty =
DependencyProperty.Register(
"CursorPosition",
typeof(int),
typeof(TestCaret),
new UIPropertyMetadata(
0,
(o, e) =>
{
if (e.NewValue != e.OldValue)
{
TestCaret t = (TestCaret)o;
t.textBox1.CaretIndex = (int)e.NewValue;
}
}));
private void textBox1_SelectionChanged(object sender, RoutedEventArgs e)
{
this.SetValue(CursorPositionProperty, textBox1.CaretIndex);
}
}

Thomas Levesque
- 286,951
- 70
- 623
- 758
-
Thanks for the reply Thomas. i'll try it out and will get back to you. – deepak Jun 11 '09 at 10:23
0
You can use the CaretIndex property. However it isn't a DependencyProperty and doesn't seem to implement INotifyPropertyChanged so you can't really bind to it.

Bryan Anderson
- 15,969
- 8
- 68
- 83