处理文本框中的光标

我的viewmodel中有一个cursorposition属性,用于决定视图中文本框中光标的位置。 如何将cursorposition属性绑定到文本框内光标的实际位置。

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

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

///  /// Interaction logic for TestCaret.xaml ///  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); } } 

您可以使用CaretIndex属性。 但是它不是DependencyProperty,似乎没有实现INotifyPropertyChanged,因此您无法真正绑定它。