MVVM and the TextBox's SelectedText property

前端 未结 3 921
名媛妹妹
名媛妹妹 2020-12-01 09:29

I have a TextBox with a ContextMenu in it. When the user right clicks inside the TextBox and chooses the appropriate MenuItem, I would like to grab the SelectedText in my v

3条回答
  •  天涯浪人
    2020-12-01 10:31

    I know it's been answered and accepted, but I thought I would add my solution. I use a Behavior to bridge between the view model and the TextBox. The behavior has a dependency property (CaretPositionProperty) which can be bound two way to the view model. Internally the behavior deals with the updates to/from the TextBox.

    public class SetCaretIndexBehavior : Behavior
        {
            public static readonly DependencyProperty CaretPositionProperty;
            private bool _internalChange;
    
        static SetCaretIndexBehavior()
        {
    
        CaretPositionProperty = DependencyProperty.Register("CaretPosition", typeof(int), typeof(SetCaretIndexBehavior), new PropertyMetadata(0, OnCaretPositionChanged));
    }
    
    public int CaretPosition
    {
        get { return Convert.ToInt32(GetValue(CaretPositionProperty)); }
        set { SetValue(CaretPositionProperty, value); }
    }
    
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.KeyUp += OnKeyUp;
    }
    
    private static void OnCaretPositionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behavior = (SetCaretIndexBehavior)d;
        if (!behavior._internalChange)
        {
            behavior.AssociatedObject.CaretIndex = Convert.ToInt32(e.NewValue);
        }
    }
    
        private void OnKeyUp(object sender, KeyEventArgs e)
        {
            _internalChange = true;
            CaretPosition = AssociatedObject.CaretIndex;
            _internalChange = false;
        }
    }
    

提交回复
热议问题