内容页访问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; }
}
模板页使用属性的时候,内容页要访问的话,必须在模板页中加入一条指令,如:
<%@ MasterType VirtualPath="~/MasterPage.master" %>
//使用Master关键字获取模板页的信息
Master.TextBoxValue = "xxx";
Master.LabelCaption= "yyy";
Master.X = "zzz";
如果不是用<%@ MasterType VirtualPath="~/MasterPage.master" %>将会编译错误,也不会出想智能提示