2009-06-11 75 views
0

我在我的視圖模型中有一個遊標位置屬性,它決定了視圖中文本框中游標的位置。我如何將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 2009-06-11 10:23:48

0

您可以使用CaretIndex屬性。然而,它不是一個DependencyProperty,也沒有實現INotifyPropertyChanged,所以你不能真正綁定它。