WPF中如果要对TextBox控件内容做限定,一般使用PreviewTextInput事件对输入内容是否符合正则表达式作判断,但是该事件有很多限制(如不能响应空格键),而在需要限定TextBox字符长度时,对于空格键的输入或者其他PreviewTextInput事件无法响应的事件需要其他方式来判断。
这里提供一种方法,使用TextChanged事件,对输入内容进行判断后把光标移动到输入末尾,达到限定长度后则无法输入的效果。代码示例:
private void username_TextChanged(object sender, TextChangedEventArgs e)
{
System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
UserNameMatch(textBox);
}
private void UserNameMatch(System.Windows.Controls.TextBox textBox)
{
if(textBox.Text.Length > 12)
{
textBox.Text = textBox.Text.Substring(0, textBox.Text.Length - 1);
textBox.SelectionStart = textBox.Text.Length;
}
}
对于Password控件同样适用,只需要修改控