2009-06-11 8 views
0

J'ai une propriété cursorposition dans mon viewmodel qui détermine la position du curseur dans la zone de texte de la vue. Comment puis-je lier la propriété cursorposition à la position réelle du curseur dans la zone de texte.Handling Cursor dans la zone de texte

Répondre

1

Je crains que vous ne pouvez pas ... au moins, pas directement, car il n'y a pas de propriété "CursorPosition" sur le contrôle TextBox.

Vous pouvez contourner ce problème en créant un DependencyProperty en code-behind, lié au ViewModel, et en gérant la position du curseur manuellement. Voici un exemple:

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

Merci pour la réponse Thomas. Je vais l'essayer et je reviendrai vers vous. – deepak

0

Vous pouvez utiliser la propriété CaretIndex. Cependant, il ne s'agit pas d'un DependencyProperty et ne semble pas implémenter INotifyPropertyChanged, donc vous ne pouvez pas vraiment vous lier à lui.

Questions connexes