Handling Cursor inside textbox
Asked Answered
A

2

0

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.

Autocratic answered 11/6, 2009 at 9:38 Comment(0)
D
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);
    }

}
Demirep answered 11/6, 2009 at 10:5 Comment(1)
Thanks for the reply Thomas. i'll try it out and will get back to you.Autocratic
H
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.

Hyaluronidase answered 29/6, 2009 at 21:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.