ASP.Net Web 窗体 - 如何从页面和用户控件设置 MasterPage 的属性
我有两个母版页,由不同的内容页使用。 我想从内容页设置母版页属性,以便母版页可以根据这些值显示一些更改。然后我还需要访问母版页中添加的用户控件中的母版页属性以反映一些更改。如何实现这一目标?
我找到了一种通过添加 <%@ MasterType VirtualPath="/Site.master" %>
然后使用 **Master.property 从内容页设置母版页属性的方法=value**
但不确定如何访问用户控件。有什么想法吗?
I have two master pages which are used by different content pages.
I want to set master page properties from content page, so that master page can show some changes based on those values. And then I also need to access those master page properties in user controls added in master page to reflect some changes. How to achieve that?
I have found a way how to set master page properties from content page by adding <%@ MasterType VirtualPath="/Site.master" %>
and then using **Master.property=value**
but not sure about how to access user control. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以创建一个基类表单,母版页从中继承该基类表单,其中包含您要存储的属性:
然后您可以从 UserControl 访问这些属性,如下所示:
You can create a base class form which your master pages inherit from that includes the properties you're looking to store:
From your UserControl, you can then access the properties as follows:
我无法得到上述答案,所以这对我有用:
您想从用户控件引用母版页属性。
首先,您的母版页将具有如下所示的公共属性:
现在在用户控件 ASCX 文件中添加对母版页的引用,如下所示:
然后在后面的代码中(在我的例子中为 C#)您有以下代码
:您的用户控件上方的母版页将无法找到母版页类。
I couldn't get the above answers to work, so here is what worked for me:
You want to reference a master page property from a user control.
Firstly, your master page will have a public property like so :
Now add a reference to the master page in the user control ASCX file like so :
Then in the code behind (C# in my case) you have this code :
Without the reference to the master page above your user control will not be able to find the master page class.
我想您可以通过两种方式访问母版页中定义的用户控件:
通过使用 FindControl 方法,为了使用它,您也必须在内容页面中添加用户控件的服务器标记,在 .aspx 页面中添加以下内容:
然后在代码隐藏:
或者您可以在母版页中创建一个返回用户控件的公共属性:
在内容页的代码隐藏中,您可以简单地通过 UserControl 属性访问此用户控件:
I guess you can access user control defined in your master page in two ways:
By using FindControl method, in order to use this you have to add the server tags for user control in content page too, in .aspx page add this:
then in code behind:
or you can create a public property in your masterpage that returns your usercontrol:
and in code behind of your content page you can access this user control simply through UserControl property:
这些控件在 Master.designer.cs 中使用访问修饰符“protected”进行定义。将其定义剪切并粘贴到代码隐藏 (Master.cs) 并将访问修饰符更改为“public”。
然后您可以访问母版页控件,如 Derek Hunziker 给出的答案所示:
The controls is defined in Master.designer.cs with access modifier "protected." Cut and paste its definition to code-behind (Master.cs) and change the access modifier to "public."
Then you can access the Master Page control as in the answer given by Derek Hunziker: