0

ビューのテキストボックス内のカーソルの位置を決定するビューモデルにcursorpositionプロパティがありました。テキストボックス内のカーソルの実際の位置にcursorpositionプロパティをバインドするにはどうすればよいですか。

4

2 に答える 2

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

}
于 2009-06-11T10:05:10.700 に答える
0

CaretIndex プロパティを使用できます。ただし、これは DependencyProperty ではなく、INotifyPropertyChanged を実装していないように見えるため、実際にバインドすることはできません。

于 2009-06-29T21:07:02.917 に答える