可以在内容页(Content)中编写代码来引用母版页(master)中的属性、方法和控件(Content),但这种引用有一定的限制。对于属性和方法的规则是:如果它们在母版页(master)上被声明为公共成员,则可以引用它们。这包括公共属性和公共方法。在引用母版页(master)上的控件(Content)时,没有只能引用公共成员的这种限制。
引用母版页(master)上的公共成员
在内容页(Content)中添加 @ MasterType 指令。在该指令中,将 VirtualPath 属性设置为母版页(master)的位置,如下面的示例所示:
复制代码
<%@ MasterType virtualpath="~/Masters/Master1.master" %>
此指令使内容页(Content)的 Master 属性被强类型化。
编写代码,将母版页(master)的公共成员用作 Master 属性的一个成员,如本例中,将母版页(master)名为 CompanyName 的公共属性的值赋给内容页(Content)上的一个文本框:
引用母版页(master)上的控件(Content)
使用 FindControl 方法,将 Master 属性的返回值用作命名容器。
下面的代码示例演示如何使用 FindControl 方法获取对母版页(master)上的两个控件(Content)的引用(一个 TextBox 控件(Content)和一个 Label 控件(Content))。因为 TextBox 控件(Content)处在 ContentPlaceHolder 控件(Content)的内部,必须首先获取对 ContentPlaceHolder 的引用,然后使用其 FindControl 方法来定位 TextBox 控件(Content)。
Visual Basic 复制代码
Sub Page_Load()
Dim mpContentPlaceHolder As ContentPlaceHolder
Dim mpTextBox As TextBox
mpContentPlaceHolder = _
CType(Master.FindControl("ContentPlaceHolder1"), _
ContentPlaceHolder)
If Not mpContentPlaceHolder Is Nothing Then
mpTextBox = CType(mpContentPlaceHolder. _
FindControl("TextBox1"), TextBox)
If Not mpTextBox Is Nothing Then
mpTextBox.Text = "TextBox found!"
End If
End If
' Gets a reference to a Label control not in a
' ContentPlaceHolder
Dim mpLabel As Label
mpLabel = CType(Master.FindControl("masterPageLabel"), Label)
If Not mpLabel Is Nothing Then
Label1.Text = "Master page label = " + mpLabel.Text
End If
End Sub