自验证文本框和Observer模式

最近写程序当中需要做一个表单提交(WinForm),当所有的表单项目符合要求时,提交按钮为可用,否则不可用,一般我们需要写一个验证的函数,然后触发TextBox的某个事件来调用函数,函数中记录下是否所有的表单项目都符合要求,是则提交按钮可用。

 


 

关于自验证本文框,在CodeProject上找到了TextBoxRegex,是一个不错的自验证TextBox。

关于Observer模式,按照四人团的说法,Observer 模式的意图是“定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新”。

 


 

直接给代码:

第一步,定义两个接口

IObserver接口:

     public   interface  IObserver
    
{
        
void Update();
        
void Attach(ISubject sub);
        
void Detach(ISubject obs);
        IList MySubject 
get;  }
    }

 

ISubject接口:

public   interface  ISubject
    
{
        IList MyObserver 
get ;  }
        
void Attach(IObserver obs);
        
void Detach(IObserver obs);
        
void Notify();
        
bool IsValided();
    }

 

第二步,写TextBox、Button控件。这里用到了TextBoxRegex

TextBox控件:

     public   class  CNWTextbox : TextBoxRegex, ISubject
    
{
        
private ArrayList obsList;
        
public CNWTextbox()
        
{
            obsList 
= new ArrayList();
            
this.UseInvalidTextException = true;
        }

        
ISubject 成员
        
protected override void OnTextChanged(EventArgs e)
        
{
            
base.OnTextChanged(e);
            
//通知所有Observer更新自己。
            Notify();
        }

        
public bool IsValided()
        
{
            
try
            
{
                
string temp = this.TextValidated;
                
return true;
            }

            
catch (Chopeen.InvalidTextException ex)
            
{
                Console.WriteLine(ex.ToString());
                
return false;
            }

        }

    }

 

Button控件:

public   class  CNWButton:Button,IObserver
    
{
        
private ArrayList mySubjects;
        
public CNWButton()
        
{
            mySubjects 
= new ArrayList();
        }

        
IObserver 成员
    }

 

第三步,使用。

cnwTextbox4,cnwTextbox5,cnwButton1是上面制作的控件。
private   void  Form1_Load( object  sender, EventArgs e)
        
{
            cnwTextbox4.Attach(cnwButton1);
            cnwTextbox5.Attach(cnwButton1);
        }

 

第四步,运行。

 

 

<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值