2009-06-11 26 views
0

私はビューのテキストボックスにカーソルの位置を決定するカーソル位置プロパティを私のviewmodelに持っていました。どのように私はカーソル位置をテキストボックス内のカーソルの実際の位置にバインドできますか?テキストボックス内のカーソルを扱う

答えて

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

返信ありがとうThomas。私はそれを試し、あなたに戻ってきます。 – deepak

0

CaretIndexプロパティを使用できます。しかし、それはDependencyPropertyではなく、実際にバインドできないようにINotifyPropertyChangedを実装していないようです。

関連する問題