【问题标题】:Handling Cursor inside textbox处理文本框中的光标
【发布时间】:2010-11-02 02:05:25
【问题描述】:

我的视图模型中有一个 cursorposition 属性,它决定了光标在视图文本框中的位置。如何将 cursorposition 属性绑定到文本框中光标的实际位置。

【问题讨论】:

    标签: c# wpf textbox cursor


    【解决方案1】:

    恐怕你不能……至少,不能直接,因为 TextBox 控件上没有“CursorPosition”属性。

    您可以通过在代码隐藏中创建一个 DependencyProperty、绑定到 ViewModel 并手动处理光标位置来解决该问题。这是一个例子:

    /// <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】:

    您可以使用 CaretIndex 属性。但是它不是一个 DependencyProperty 并且似乎没有实现 INotifyPropertyChanged 所以你不能真正绑定到它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      • 2011-05-23
      • 2012-03-07
      相关资源
      最近更新 更多