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.
Handling Cursor inside textbox
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);
}
}
Thanks for the reply Thomas. i'll try it out and will get back to you. –
Autocratic
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.
© 2022 - 2024 — McMap. All rights reserved.