動態加載用戶控件的組件!
2024-07-21 02:27:37
供稿:網友
我們寫用戶控件的目的就是放到頁面中去。根據不同的條件,我們可以改變加載的用戶控件!
其實原理就是masterpage的原理。這個masterpage會在vs2005中提供,但是現在也可以實現。
在我的項目中就用到:
masterpage就四個類,其中容器就動態加載用戶控件。這種功能在vs2005中將無處不在。
下面簡單介紹一下動態加載葉面組件:
我們只需要改變用戶組件的地址就可以動態改變加載的用戶組件了。
在程序中動態改變skinpath就可以了。
組件源碼如下:
using system;
//using system.drawing;
using system.collections;
using system.collections.specialized;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;
using system.componentmodel;
using system.io;
using system.web.security;
using region.components;
namespace region.controls {
[parsechildren(true)]
/// <summary>
/// 頁面組件,從用戶組件獲取
/// </summary>
public abstract class skinnedcontrol : webcontrol, inamingcontainer {
string skinfilename = null;
string skinname = null;
string skinpath;
// string returnurl = null;
/// <summary>
/// 添加子組件
/// </summary>
protected override void createchildcontrols() {
if(skinpath == null || skinpath == "" || skinpath.trim() == "")
return ;
control skin;
skin = loadskin();
initializeskin(skin);
controls.add(skin);
}
/// <summary>
/// 獲取摸板組件
/// </summary>
/// <returns>組件</returns>
protected control loadskin()
{
control skin;
try
{
skin = page.loadcontrol(skinpath);
}
catch (filenotfoundexception)
{
throw new exception("找不到文件:[ " + skinpath + " ] .");
}
return skin;
}
/// <summary>
/// 初始化組建摸板
/// </summary>
/// <param name="skin">組件</param>
protected abstract void initializeskin(control skin);
/// <summary>
/// 用戶組件名稱
/// </summary>
public string skinfilename
{
get
{
return skinfilename;
}
set
{
skinfilename = value;
}
}
/// <summary>
/// 組件名稱
/// </summary>
protected string skinname
{
get
{
return skinname;
}
set
{
skinname = value;
}
}
/// <summary>
/// 用戶組件相對路徑及組件名稱
/// </summary>
public string skinpath
{
get
{
return skinpath;
}
set
{
skinpath = value;
skinfilename = value.trimstart('/');
}
}
}
}
比如我的一個應用:
switch (context.pageid)
{
case "1_1" :
base.skinpath = "~/themes/signmanager/termlist.ascx";
break ;
case "1_1_1" :
base.skinpath = "~/themes/signmanager/termedit.ascx";
break ;
case "1_2" :
base.skinpath = "~/themes/signmanager/memberlist.ascx";
break ;
case "1_2_1" :
base.skinpath = "~/themes/signmanager/memberedit.ascx";
break ;
case "2_1" :
base.skinpath = "~/themes/signmanager/cardsend.ascx";
break ;
case "3_1" :
base.skinpath = "~/themes/signmanager/membernoedit.ascx";
break ;
case "4_1" :
base.skinpath = "~/themes/acountedit.ascx";
break ;
default :
base.skinpath = "";
break;
}
基于組建的開發,我們可省去葉面上很多重復性的地方。只需在重復葉面的地方引用組件就可以了
比如:
這樣我們就可以 以用戶組件為元素,組件不同的葉面。葉面也可以重用!