MasterPages 是类,就像普通的 Page 对象一样。这意味着您可以通过公共属性公开内部控制,以允许子页面访问,而无需求助于 Master.FindControl()。为此,您只需要在页面中设置 MasterType 属性(我认为即使不设置它也可以工作,但这样您可以获得智能感知支持并避免进行强制转换)。
这是一个基本示例(对不起,它是在 VB 中 - 这是从旧项目中复制和粘贴):
母版页 (.master):
<%@ Master Language="VB" CodeFile="default.master.vb" Inherits="DefaultMaster" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
<ASP:TextBox ID="Search" RunAt="Server"/>
<ASP:ContentPlaceHolder ID="Content" RunAt="Server"/>
</form>
</body>
</html>
主代码隐藏 (.master.vb):
Partial Class DefaultMaster : Inherits MasterPage
Public ReadOnly Property SearchBox() As TextBox
Get
Return Search
End Get
End Property
End Class
访问页面(.aspx):
<%@ Page Language="VB" MasterPageFile="default.master" CodeFile="page.aspx.vb" Inherits="ExamplePage" %>
<%@ MasterType TypeName="DefaultMaster" %>
<ASP:Content ContentPlaceHolderID="Content" RunAt="Server">
<p>This is some content on the page.</p>
</ASP:Content>
访问页面代码隐藏 (.aspx.vb):
Partial Class ExamplePage : Inherits Page
Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs) Handles MyBase.Load
Master.SearchBox.Text = "This page now has access to the master's search box."
End Sub
End Class