Search code examples
c#wpftextboxcustom-controlstextchanged

How to find WPF TextBox's changed text?


Suppose we inherit from WPF TextBox and then try to get text changes through overriding OnTextChanged.

Then we would notice when changes occurred, but the only information that we would have is:

  • Offset that this change occurred
  • Removed Length
  • Added Length

Can we get the accurate added text by using,

Text.Substring(Change.Offset, Change.AddedLength) 

in OnTextChanged?

Text Change occurs in different conditions (such as user input, pasting text, or setting Text property in-code). Is there any possibility of conflicting changes coming into e.Changes?

Is this approach a trust way? If answer is No, Is there any other standard way(s) to get accurate changed text?


Solution

  • For a TextBox, this event occurs when its text changes; for a RichTextBox, this event occurs when any content or formatting changes (for example, images, table, or background color).

    1. Can we get the accurate added text by using ... ?

    Yes, you will always get accurate text in case of TextBox. You can make use of e.UndoAction to check for addition/deletion of text. Read documentation here.

    1. Is there any possibility of conflicting changes coming into e.Changes?

    There won't be conflicting changes.

    In general, the following will always be true:

    • The changes that occur result in the document being in a valid state. The collection is ordered consecutively, related to where the change occurred in the control. For example, a TextChange object that represents a change at position 2 is before a TextChange object that represents a change at position 10.

    • Two TextChange objects do not represent an overlapping area. The value of Offset plus the value of AddedLength of one TextChange
      object is always less than or equal to the value of Offset of the
      next TextChange object in the collection. Likewise, the value of
      Offset plus the value of RemovedLength of one TextChange object is
      always less than or equal to the value of Offset of the next
      TextChange object in the collection.

    • The collection reflects whatever changes occurred, even if there seems to be no net change. In the preceding example, neither the
      first or fourth change results in a net change, because each simply
      removed and re-added the and symbols, respectively. But
      the symbols were actually removed and added, so they are included in
      the collection.

    More can be read here.