2009-06-11 15 views
0

Ich hatte eine Cursorposition Eigenschaft in meinem Viewmodel, die die Position des Cursors in Textfeld in der Ansicht entscheidet. Wie kann ich die cursorposition -Eigenschaft an die tatsächliche Position des Cursors innerhalb des Textfelds binden.Handhabung Cursor in Textfeld

Antwort

1

Ich fürchte, Sie können nicht ... zumindest nicht direkt, da es keine "CursorPosition" -Eigenschaft auf das TextBox-Steuerelement gibt.

Sie können dieses Problem umgehen, indem Sie in Code-Behind eine DependencyProperty erstellen, die an das ViewModel gebunden ist und die Cursorposition manuell verarbeitet. Hier ein Beispiel:

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

Danke für die Antwort Thomas. Ich werde es ausprobieren und werde zu dir zurückkommen. – deepak

0

Sie können die CaretIndex-Eigenschaft verwenden. Es ist jedoch keine DependencyProperty und scheint INotifyPropertyChanged nicht zu implementieren, sodass Sie nicht wirklich daran binden können.