How to check length of added text in TextBox TextBox WPF event?

I have a TextChanged event for my WPF text field as follows:

 private void textMatch_TextChanged(object sender, TextChangedEventArgs e) { var m = e.Changes;//here I can see e.Changes has what I'm looking for //do some other stuff here. } 

However, I want to check the length of the text that was added. Apparently, e.Changes contains this value, but I cannot find a way to find it programmatically and cannot find any example on the Internet.

My current way of checking this is to keep the current length each time the text is changed and make sure that the new length only increases by 1, but this seems like a hack for me.

Has anyone tried this before? How to find out the length of added text using TextChangedEventArgs ? Thanks.

+4
source share
2 answers

What you are looking for is extracting a TextChange object from the e.Changes TextChange collection. The following should work:

 int added = e.Changes.ElementAt(0).AddedLength; 

However, if you need something more specific, you can use:

 int added = e.Changes.FirstOrDefault().AddedLength; 

Since e.Changes , as far as I know, will always contain one TextChange element at the TextChange , I think it will always be the first even in future WPF TextBox implementations.

For an implementation without Linq , which seems completely unnecessary to me, you can use the following cumbersome code:

 var x = e.Changes.GetEnumerator(); x.MoveNext(); int added = x.Current.AddedLength; 
+3
source

For a TextBox, it seems that count will always be 1, since a TextBox cannot contain anything but characters.

But I found this search for answers regarding TextChange, and just want to let others know that TextChange.Changes.Count can be more than 1 when used with RichTextBox.

This result can be a bit confusing.

If you are just learning how to work with this, keep in mind that whether you enter a single character or insert multiple lines, Count may be 1.

But a change in a font family can include several changes; in fact, it seems that for 1 selected word, the changed font family is applied. However, on the other hand, changes to Font Size, Underline, Bold, or Italics can result in Count = 0.

With RichTextBox, TextChange is the result of a character change, not a character change. So you can insert β€œHello To All The World” and get one TextChange, because it is one text element containing nested text.

0
source

All Articles