How do I find what text had been added with TextChanged

后端 未结 2 956
醉话见心
醉话见心 2021-01-27 10:23

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 add

2条回答
  •  天命终不由人
    2021-01-27 10:55

    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 = "";
                }
            }
        }
    

提交回复
热议问题