【问题标题】:ASP.Net Web Forms - How to set properties of MasterPage from page and user controlsASP.Net Web 窗体 - 如何从页面和用户控件设置 MasterPage 的属性
【发布时间】:2011-08-05 00:56:30
【问题描述】:
我有两个母版页,供不同的内容页使用。
我想从内容页面设置母版页属性,以便母版页可以根据这些值显示一些更改。然后我还需要访问母版页中添加的用户控件中的母版页属性以反映一些更改。如何实现?
我找到了一种方法,如何通过添加 <%@ MasterType VirtualPath="/Site.master" %> 然后使用 **Master.property=value** 从内容页面设置母版页属性,但不确定如何访问用户控件。有什么想法吗?
【问题讨论】:
标签:
c#
asp.net
user-controls
master-pages
【解决方案1】:
您可以创建一个基类表单,您的母版页继承自该表单,其中包括您要存储的属性:
abstract public class MasterPageBase : System.Web.UI.MasterPage
{
public string Prop1
{
get { return "Some Value"; }
}
}
然后,您可以从您的 UserControl 访问属性,如下所示:
MasterPageBase masterPage = (MasterPageBase)this.Page.Master;
string strTest = masterPage.Prop1; // "Some Value"
【解决方案2】:
我无法得到上述答案,所以这对我有用:
您想从用户控件中引用母版页属性。
首先,您的母版页将具有这样的公共属性:
public string BodyClass
{
set
{
this.masterBody.Attributes.Add("class", value);
}
}
现在在用户控件 ASCX 文件中添加对母版页的引用,如下所示:
<%@ Register Src="~/Source/MasterPages/Main.master" TagPrefix="MSTR" TagName="MasterPage" %>
然后在后面的代码中(在我的例子中是 C#)你有这个代码:
Main masterPage = (Main)this.Page.Master;
masterPage.BodyClass = "container";
如果不引用您的用户控件上方的母版页,您将无法找到母版页类。
【解决方案3】:
我猜您可以通过两种方式访问母版页中定义的用户控件:
通过使用 FindControl 方法,为了使用它,您还必须在内容页面中添加用户控件的服务器标签,在 .aspx 页面中添加:
<%@ Register Src="~/myControl.ascx" TagName="myControl" TagPrefix"uc" %>
然后在后面的代码中:
myControl = (myControl)this.Page.Master.FindControl("userControl_Id");
或者您可以在您的母版页中创建一个公共属性来返回您的用户控件:
public myControl UserControl { get; set; }
在内容页面后面的代码中,您可以通过 UserControl 属性访问此用户控件:
myControl ctrl = (myControl)this.Page.Master.UserControl;
【解决方案4】:
控件在 Master.designer.cs 中定义,访问修饰符为“protected”。将其定义剪切并粘贴到代码隐藏 (Master.cs) 中,并将访问修饰符更改为“public”。
然后您可以按照 Derek Hunziker 给出的答案访问 Master Page 控件:
MasterPageBase masterPage = (MasterPageBase)this.Page.Master;
string strTest = masterPage.Prop1; // "Some Value"