TextBox TextChanged event on programmatic versus user change of text contents

后端 未结 8 1728
日久生厌
日久生厌 2020-12-15 18:16

I would like to differentiate between changing the text programmatically (for example in a button click handler event) and user input (typing, cutting and pasting text). <

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 18:56

    Partial credits for dodgy_coder (agreed not conform the beautiful design you hope for, but imo the best compromis). Consider everything you want to cover:

    1. move text by dragging with mouse from TB2 to TB1
    2. cut (ctrl-x, programmatic cut, mouse-menu-cut)
    3. paste (ctrl-v, programmatic paste, mouse-menu-paste)
    4. undo (ctrl-z, programmatic undo)
    5. redo (ctrl-Y, programmatic redo)
    6. delete & backspace
    7. keyboard text (alfanumeric + symbols + space)

    Consider what you want to exclude:

    1. programmatic setting of Text

    Code

    public class MyTB : TextBox
    {
        private bool _isTextProgrammaticallySet = false;
    
        public new string Text
        {
            set
            {
                _isTextProgrammaticallySet = true;
                base.Text = value;
                _isTextProgrammaticallySet = false;
            }
        }
    
        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            base.OnTextChanged(e);
    
            // .. on programmatic or on user
    
    
            // .. on programmatic
            if (_isTextProgrammaticallySet)
            {
    
    
                return;
            }
    
            // .. on user
            OnTextChangedByUser(e);
        }
    
        protected void OnTextChangedByUser(TextChangedEventArgs e)
        {
            // Do whatever you want.
        }
    }
    

    The following is discouraged, but the results of an attempt to cover all:
    The alternatives for catching all the events were:

    • DataObject.AddPastingHandler(MyTextBox, MyPasteCommand);
      Covers 1 & 3
    • OnPreviewTextInput
      Covers 7 but not space
    • OnKeyDown
      Covers 7-space

    Trying to cover 2, 4, 5, 6 & 8 I figured I should go with the easier and consistent solution above :)

提交回复
热议问题