本文主要是介绍“回发”的一点总结,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
说来惭愧,接触.net一载有余,在和Clingingboy学习控件开发的时候,期间就提到了控件的“回发事件”和“数据回发事件”,当时就晕了头(由于本人愚笨),后来google了一些资料,才发现“原来就是这样的”,希望这”半纸荒唐言“,能对那些还没有亦或即将明白的朋友尽点微薄之力!
在这里,回发事件,我给她起个名字,叫“动作回发事件”,一般就是OnClick回发事件!
数据回发,当postback后,页面在processPostData事件中,调用控件的LoadPostData方法,此方法检查新提交的数据,判断是否与原来的值相同,如果不相等,则更新值,然后控件自动调用RaisePostDataChangedEvent方法!一句话,数据回发就是用来更新值的(在此方法中,可以激活下面的“回发数据事件”)
数据回发事件,可以这样理解,当触发“动作回发事件”后,控件的值Text如果与原来的Text不相同!由于新值与旧值不同而引发的事件!就叫数据回发事件!
一,先看看“动作回发事件”的代码!
publicclassCustomePostBackEventButton:Control,IPostBackEventHandler
{
//声明Click事件委托
publiceventEventHandlerClick;
//定义OnClick事件处理程序
protectedvirtualvoidOnClick(EventArgse)
{
if(Click !=null)
{
Click(this, e);
}
}
//实现RaisePostBackEvent方法,处理回发事件
//这里就是系统激活“动作回发事件”的入口
publicvoidRaisePostBackEvent(stringeventArgument)
{
OnClick(newEventArgs());
}
protectedoverridevoidRender(HtmlTextWriteroutput)
{
output.Write("<input type=submit name="+this.UniqueID +" Value='确定' />");
}
}
代码很简单,继承了处理“动作回发事件”的IPostBackEventHandler接口,并实现了激活“动作回发事件”的入口方法RaisePostBackEvent!在这里,因为Click事件是由RaisePostBackEvent方法激活,所以Click就是一个“动作回发事件”!
二,数据回发事件的代码!
publicclassCustomePostDataEventTextbox : Control, IPostBackDataHandler
{
publicstringText
{
get
{
objecttext = ViewState["Text"];
if(text ==null)
returnstring.Empty;
else
return(string)text;
}
set
{
ViewState["Text"] =value;
}
}
publicboolLoadPostData(stringpostDataKey,NameValueCollection postCollection)
{
stringpostedValue = postCollection[postDataKey];
//检查新旧数据
if(!Text.Equals(postedValue))
{
Text = postedValue;
returntrue;
//自动调用
RaisePostDataChangedEvent()
}
else
returnfalse;
//不发生变化
}
publicvoidRaisePostDataChangedEvent()
{
OnTextChanged(EventArgs.Empty);
}
protectedvirtualvoidOnTextChanged(EventArgse)
{
if(TextChanged !=null)
TextChanged(this, e);
}
publiceventEventHandlerTextChanged;
overrideprotectedvoidRender(HtmlTextWriter writer)
{
base.Render(writer);
Page.VerifyRenderingInServerForm(this);
writer.Write("<INPUT type=/"text/" name=/"");
writer.Write("/" value=/""+this.Text +"/" />");
}
}
可以看到自定义的TextBox继承了,接口IPostBackDataHandler,并实现了LoadPostData方法和RaisePostDataChangedEvent方法! 注意,此时的TextChanged事件由,专门用来处理回发数据的RaisePostDataChangedEvent方法激活,所以TextChanged就是数据回发事件!
总结,
要区分“动作回发事件”和“数据回发事件”,就要看事件是被哪一个方法激活的,如果事件被RaisePostBackEvent方法激活,那事件就是一般的“动作回发事件”;如果被RaisePostDataChangedEvent方法激活,那么就是“数据回发事件”!
备注,
这篇关于“回发”的一点总结的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!