很早就在看了,一直沒寫,現(xiàn)在記錄下.以后可能用到比較多.
Extender控件本身并不對(duì)原有控件進(jìn)行更改,而是進(jìn)行擴(kuò)展.可以說是前臺(tái)固定的js文件加上一些后臺(tái)生成的一些參數(shù)進(jìn)行配合,來對(duì)前臺(tái)顯示的控件進(jìn)行業(yè)務(wù)操作.廢話不多說.看教程來學(xué)習(xí)下.
1.定義一個(gè)繼承自ExtenderControl類的控件擴(kuò)展類
public class FocusExtender : ExtenderControl
{
}
2.定義元屬性
TargetControlType指定擴(kuò)展類型
[TargetControlType(typeof(Control))]
3.重寫GetScriptReferences和GetScriptDescriptors方法
(1)GetScriptReferences方法用于加載js文件集合
(2)GetScriptDescriptors方法用于添加控件行為描述,不好意思不知道怎么描述,反正就是為控件添加屬性,事件等一些東西.
PRotected override IEnumerable<ScriptReference> GetScriptReferences()
{
ScriptReference reference = new ScriptReference();
reference.Path = ResolveClientUrl("FocusBehavior.js");
return new ScriptReference[] { reference };
}
protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors(Control targetControl)
{
ScriptBehaviorDescriptor descriptor = new ScriptBehaviorDescriptor("Samples.FocusBehavior", targetControl.ClientID);
descriptor.AddProperty("highlightCSSClass", this.HighlightCssClass);
descriptor.AddProperty("nohighlightCssClass", this.NoHighlightCssClass);
return new ScriptDescriptor[] { descriptor };
}
4.編寫js文件
根據(jù)asp.net Ajax框架的方法,將其寫成類的形式
(1)添加事件,注意沒有"on"
//初始化
initialize : function() {
Samples.FocusBehavior.callBaseMethod(this, 'initialize');
$addHandlers(this.get_element(),
{ 'focus' : this._onFocus,
'blur' : this._onBlur },
this);
this.get_element().className = this._nohighlightCssClass;
},
//釋放
dispose : function() {
$clearHandlers(this.get_element());
Samples.FocusBehavior.callBaseMethod(this, 'dispose');
},
屬性以get,set方法定義,set方法后面記得調(diào)用raisePropertyChanged方法
get_highlightCssClass : function() {
return this._highlightCssClass;
},
set_highlightCssClass : function(value) {
if (this._highlightCssClass !== value) {
this._highlightCssClass = value;
this.raisePropertyChanged('highlightCssClass');
}
},
get_nohighlightCssClass : function() {
return this._nohighlightCssClass;
},
set_nohighlightCssClass : function(value) {
if (this._nohighlightCssClass !== value) {
this._nohighlightCssClass = value;
this.raisePropertyChanged('nohighlightCssClass');
}
}
以上差不多就好了,其實(shí)還是抓住幾個(gè)參數(shù)來進(jìn)行設(shè)置,然后再呈現(xiàn)出來.上面的例子沒有改變?cè)锌丶?而是創(chuàng)建Extender控件,你也可以擴(kuò)展原有控件
.那則需要實(shí)現(xiàn)IScriptControl接口.其實(shí)還是一樣需要實(shí)現(xiàn)GetScriptReferences方法GetScriptDescriptors方法,多做的事就是需要自己手動(dòng)用ScriptManager控件來注冊(cè)一下.
protected override void OnPreRender(EventArgs e)
{
if (!this.DesignMode)
{
// Test for ScriptManager and register if it exists
sm = ScriptManager.GetCurrent(Page);
if (sm == null)
throw new HttpException("A ScriptManager control must exist on the current page.");
sm.RegisterScriptControl(this);
}
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
if (!this.DesignMode)
sm.RegisterScriptDescriptors(this);
base.Render(writer);
}
最后還要記得js里面也要注冊(cè)下,Extender控件為Sys.UI.Behavior,這次為Sys.UI.Control
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注