2009-06-11 4 views
0

У меня было свойство cursorposition в моей модели viewmodel, которое определяет положение курсора в текстовом поле на представлении. Как я могу привязать свойство cursorposition к фактическому положению курсора внутри текстового поля.Обработка курсора внутри текстового поля

ответ

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

} 
+0

Спасибо за ответ Томаса. я попробую и вернусь к вам. – deepak

0

Вы можете использовать свойство CaretIndex. Однако это не DependencyProperty и, похоже, не реализует INotifyPropertyChanged, поэтому вы не можете привязываться к нему.

Смежные вопросы