[英]How can I get the text from the TextBox_KeyDown event? WPF C#
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 )??如何获取新文本(使用用户添加的密钥)?
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.
通常应该使用 TextChanged 事件来检测 TextBox 或 RichTextBox 中的文本何时发生变化,而不是您可能期望的 KeyDown。
If you need the KeyDown
event, obviously you can't rely on the text being set.如果您需要
KeyDown
事件,显然您不能依赖正在设置的文本。 Otherwise, you should use the TextChanged
event.否则,您应该使用
TextChanged
事件。
Edit:编辑:
As someone pointed out in the comments, OnPreviewTextInput
could serve your purpose.正如有人在评论中指出的那样,
OnPreviewTextInput
可以达到您的目的。 You have a bit more control via the TextCompositionEventArgs
.您可以通过
TextCompositionEventArgs
进行更多控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.