wpf 一次只接受一个字符的文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16134769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
textbox to accept only one character at a time
提问by user2151660
I need to make a TextBoxcontrol accept only one character at a time. For instance if I input "aaa", then it would only accept "a".
我需要让TextBox控件一次只接受一个字符。例如,如果我输入"aaa",那么它只会接受"a"。
How can I accomplish this?
我怎样才能做到这一点?
回答by Farhad Jabiyev
TextBox has a MaxLengthproperty. MaxLengthgets or sets the maximum number of characters that can be manually entered into the text box.
TextBox 有一个MaxLength属性。MaxLength获取或设置可以手动输入到文本框中的最大字符数。
<TextBox MaxLength="1" Width="120" Height="23" />
So here, you can enter only one character manually.
所以在这里,您只能手动输入一个字符。
回答by keyboardP
If I understand correctly, you don't want the user to be able to enter the same key more than once in a row. This should prevent that:
如果我理解正确,您不希望用户能够连续多次输入相同的密钥。这应该可以防止:
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if(textBox != null)
{
if (!String.IsNullOrEmpty(textBox.Text))
{
//get the last character and convert it to a key
char prevChar = textBox.Text[textBox.Text.Length - 1];
Keys k = (Keys)char.ToUpper(prevChar);
//compare the Key pressed to the previous Key
if (e.KeyData == k)
{
//suppress the keypress if the key is the same as the previous one
e.SuppressKeyPress = true;
}
}
}
}

