如果用到MastePage.有时候,我们需要在开发过程中在ContentPage访问masterpage中的属性,方法或者控件的信息。这个Demo说明了如何来实现这样的作业>
其实很简单,关键的一步是要在contentpage中“声明”对masterpage的"引用":
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="contentpage1.aspx.cs" Inherits="contentpage1" %>
<%@ MasterType VirtualPath ="~/MasterPage.master" %> <%--在这里声明--%>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>
然后,在contentpage中就可以访问masterpage public的属性和方法,以及其控件.
masterpage HTML:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>My MasterPage Title</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblheader" runat="server" Text="Label"></asp:Label>
<br />
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
</div>
<div>
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</div>
</form>
</body>
</html>
masterpage CS:
public partial class MasterPage : System.Web.UI.MasterPage
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
this.lblheader.Text = title;
}
public void GetTitle()
{
txt.Text = "i will go";
}
}
在masterpage中定义了一个属性,一个方法。
contentpage:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.Title = "masterpage title here";
Master.Title = "Access To masterPage''s property";
Master.GetTitle();
TextBox txt= Master.FindControl("txt") as TextBox;
txt.BackColor = System.Drawing.Color.Red;
}
可以看到,无论是属性,方法,控件都是可以访问的.