WPF TextBox 不允许空格。
WPF TextBox 不允许空格。
这个问题已经有答案了:
我想让用户只能在TextBox中输入数字(0-9)。
我使用以下代码来防止用户输入字母和其他字符,但我不能防止用户在TextBox中使用空格。
private void CheckIsNumeric(TextCompositionEventArgs e) { int result; if (!(int.TryParse(e.Text, out result))) { e.Handled = true; MessageBox.Show("!!!no content!!!", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); } }
我尝试使用类似于以下代码的东西:
if (Keyboard.IsKeyDown(Key.Space)) { //...}
但并没有成功。
谢谢帮助。
admin 更改状态以发布 2023年5月23日
在检查之前,请检查分隔空格,或者只是更正空格。因此用户可以尽可能使用空格,而不会改变任何内容。
private void CheckIsNumeric(TextCompositionEventArgs e) { int result; string removedSpaces = e.Text.Replace(" ",""); if (!(int.TryParse(removedSpaces, out result))) { e.Handled = true; MessageBox.Show("!!!no content!!!", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); } }
为您的文本框注册KeyPress事件,并添加以下代码。
private void textBox_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // If you want to allow decimal numeric value in you textBox then add this too if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } }