Handling Cursor inside textbox

喜夏-厌秋 提交于 2019-12-23 04:53:09

问题


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.


回答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);
    }

}



回答2:


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.



来源:https://stackoverflow.com/questions/980219/handling-cursor-inside-textbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!