Search code examples
wpftextboxtextchanged

How do I find what text had been added with TextChanged


I'm looking to synchronize between a text in the textbox and string in a variable. I found how to get the index in which the string was changed (in the textbox), the length added and length removed, but how can I actually find the string added?

So far I've used TextChangedEventArgs.Changes, and got the properties of the items in it (ICollection).

I'm trying to create a password box in which I could show the actual password by a function. hence I do not want the textbox to synchronize directly (for example, in the textbox would appear "*****" and in the string "hello").


Solution

  • If you want only text added you can do this

     string AddedText;
     private void textbox_TextChanged(object sender, TextChangedEventArgs e)
     {
         var changes = e.Changes.Last();
         if (changes.AddedLength > 0)
         {
             AddedText = textbox.Text.Substring(changes.Offset,changes.AddedLength);
         }
     }
    

    Edit

    If you want all added and remove text you can do this

        string oldText;
        private void textbox_GotFocus(object sender, RoutedEventArgs e)
        {
            oldText = textbox.Text;
        }
    
        string AddedText;
        string RemovedText;
        private void textbox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var changes = e.Changes.Last();
            if (changes.AddedLength > 0)
            {
                AddedText = textbox.Text.Substring(changes.Offset, changes.AddedLength);
                if (changes.RemovedLength == 0)
                {
                    oldText = textbox.Text;
                    RemovedText = "";
                }
            }
            if (changes.RemovedLength > 0)
            {
                RemovedText = oldText.Substring(changes.Offset, changes.RemovedLength);
                oldText = textbox.Text;
                if (changes.AddedLength == 0)
                {
                    AddedText = "";
                }
            }
        }