您的位置:首页 > 其它

MasterPageFile 模板页使用总结

2010-05-21 14:40 369 查看
MasterPageFile 模板页使用总结

1.模板页扩展名为Master,内容页引用模板页的方法:

2.动态改变内容页所引用的模板页 通常在Init事件下改变:

protected void Page_PreInit(object sender,EventArgs e) {this.MasterPageFile="~/ABC.master";}


3.在内容页中使用模板页中的控件 Master: 内容页:

Label lb = (Label)Master.FindControl("LabDemo");//直接在Master中找LabDemo
if (lb != null)
{
Response.Write("");
}


当控件在Master中的ContentPlaceHolder里的话则需要:

ContentPlaceHolder a = (ContentPlaceHolder)Master.FindControl("Content2");//先找到ContentPlaceHolder的ID
if(a!= null)
{
TextBox Txt=(TextBox)a.FindControl("TxtDemo");
if(Txt != null)
{
Response.write(Txt.text.ToString());
}
}


4.在内容页中使用模板页中的变量,属性,方法 首先在内容页加上:

模板页中的变量必须为:Public string WebTitle="welocome to ..."; //并放在模板页类下定义并初始化. 就可以在内容页中:Master.WebTitle进行引用. 但如果此变量在网页加载的时候改变了,引用的值还为定义时初始化的值.因为加加载模板页到内容页的事件先后为:

(1)母版页-Init

(2)内容页-Init

(3)内容页-Load

(4)母版页-Load

(5)内容页-PreRender

(6)母版页-PreRender 所以,要改变变量的值应放在:母版页中的Init事件中,放在Load事件中是不行的.

例:

protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
WebConfigSelect();//此方法对变量进行了初始化或者改变!
}
}


引用 .net 包含其他页面一般使用用户控件或模板:

内容页访问MasterPage中的控件,有两种解决方案:

一、是用弱类型访问 使用 FindControl 方法获取模板页的控件

((Label)Master.FindControl("Label1")).Text = "xxx";

二、给模板页添加属性来使用强类型访问(推荐) 模板页定义;

//属性
private string x;
public string X
{
get
{
return this.x;
}
set
{
this.x = value;
}
}
//控件的属性以属性的形式公开给内容页

public string LabelCaption
{
get
{
return this.Label1.Text;
}
set
{
this.Label1.Text = value;
}
}


模板页使用属性的时候,内容页要访问的话,必须在模板页中加入一条指令,

如:

//使用Master关键字获取模板页的信息
Master.TextBoxValue = "xxx";
Master.LabelCaption= "yyy";
Master.X = "zzz";


如果不是用将会编译错误,也不会出想智能提示

5.模板页或内容页中的路径最好使用"~/"而不要使用相对路径
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: