关于画面内容的check的设计
首先定义接口
public interface IValidator {
void Validate(object value);}及虚类
public abstract class AbstractValidator {
private string errorMessage;
public string ErrorMessage { get { return errorMessage; } set { errorMessage = value; } }protected bool IsEmptyString(object obj) {
if (obj == null || obj.ToString() == string.Empty) { return true; } else { return false; } }public AbstractValidator() {
return; }}然后定义各个具体的check类,比如只能输入半角英数字的check
public class AlphabetAndNumberValiator : AbstractValidator, IValidator {
public void Validate(Object value) {
Regex regex = new Regex(@"[a-zA-Z0-9]"); if (!regex.IsMatch(value.ToString())) { throw new ValidatorException(this.ErrorMessage); } }public AlphabetAndNumberValiator() {
this.ErrorMessage = "请输入半角英数字"; }}最后定义容器
public class ActiveValidator {
private ErrorProvider errorProvider;
private Dictionary<Control, List<IValidator>> dic = new Dictionary<Control, List<IValidator>>();
private bool isAutoAddEventHandler = true;
public bool IsAutoAddEventHandler { get { return isAutoAddEventHandler; } set { isAutoAddEventHandler = value; } }public void AddValidator(Control control, IValidator validator) {
if (dic.ContainsKey(control)) { if (dic[control].Contains(validator) == false) { dic[control].Add(validator); } } else { List<IValidator> list = new List<IValidator>(); list.Add(validator); dic.Add(control, list); control.Validating += new CancelEventHandler(this.DoValidation); } }public bool DoAllValidation() {
this.errorProvider.Clear(); bool ret = false; foreach (Control control in dic.Keys) { foreach (IValidator validator in dic[control]) { try { validator.Validate(control.Text); } catch (ValidatorException ex) { this.errorProvider.SetError(control, ex.Message); ret = true; } } } return ret; }private void DoValidation(object sender, EventArgs e) {
if (this.isAutoAddEventHandler) { this.errorProvider.Clear(); Control control; if (sender is Control) { control = (Control)sender; } else { return; } List<IValidator> list; if (dic.ContainsKey(control)) { list = dic[control]; } else { return; } foreach (IValidator validator in list) { try { validator.Validate(control.Text); } catch (ValidatorException ex) { this.errorProvider.SetError(control, ex.Message); // TODO } } } }public ActiveValidator(ErrorProvider errorProvider) {
this.errorProvider = errorProvider; }}
画面类追加例
this.validator = new ActiveValidator(this.errorProvider);
this.validator.AddValidator(this.TextBox1, new AlphabetAndNumberValiator());同时,在提交button的click事件中,也可以调用this.validator.DoAllValidation(),做全画面注册控件的check.