1 /// <summary> 2 /// 使用正则表达式限制输入 3 /// </summary> 4 public class TextBoxRegex : TextBox 5 { 6 // 正则表达式,只含有汉字、数字、字母、下划线不能以数字开头 7 private const string NamimgPattern = "^(?![0-9])[a-zA-Z0-9_u4e00-u9fa5]{1,30}$"; 8 9 public TextBoxRegex() 10 { 11 TextChanged += TextBoxRegex_TextChanged; 12 } 13 14 private void TextBoxRegex_TextChanged(object sender, TextChangedEventArgs e) 15 { 16 //屏蔽非法字符粘贴 17 var textBox = sender as TextBox; 18 if (textBox != null) 19 { 20 var change = new TextChange[e.Changes.Count]; 21 e.Changes.CopyTo(change, 0); 22 23 int offset = change[0].Offset; 24 if (change[0].AddedLength > 0) 25 { 26 if (!Regex.IsMatch(textBox.Text, NamimgPattern, RegexOptions.IgnoreCase)) 27 { 28 // 不符合正则表达式时移除内容,设置光标位置 29 textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength); 30 textBox.Select(offset, 0); 31 } 32 } 33 } 34 } 35 }