Home > Mobile >  How can I get the text from the TextBox_KeyDown event? WPF C#
How can I get the text from the TextBox_KeyDown event? WPF C#

Time:05-18

I have this event and I would like to get the text from the user input dynamically ( real time ) , so when the user type any character, it should be added to the currently text and I have the possibility to get it .

 public void TextBox_KeyDown(object sender, KeyEventArgs e) {
     TextBox text = (TextBox) sender;
     string myText = text.Text; // will return the old text in the textbox
 }

How can I get the new text ( with the key added by the user )??

CodePudding user response:

From the documentation

Usually the TextChanged event should be used to detect whenever the text in a TextBox or RichTextBox changes rather then KeyDown as you might expect.

If you need the KeyDown event, obviously you can't rely on the text being set. Otherwise, you should use the TextChanged event.

Edit:

As someone pointed out in the comments, OnPreviewTextInput could serve your purpose. You have a bit more control via the TextCompositionEventArgs.

  • Related