C# 如何从内容页面访问母版页中的用户控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/382358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a user control in a masterpage from a content page?
提问by Bryan Denny
Lets say that I have a header user control in a master page, and want to change a property of the user control depending on what content page is loaded inside of the master page. How might I go about this?
假设我在母版页中有一个标题用户控件,并且想要根据在母版页内加载的内容页来更改用户控件的属性。我该怎么办?
Thanks!
谢谢!
采纳答案by Shawn
You can use two methods. The first is by using Page.Master.FindControl('controlID')
. Then you can cast it to the type of your user control. The second method is by adding a <%@ MasterType VirtualPath="">
OR <%@ MasterType TypeName=""%>
tag to your aspx page. In the VirtualPath
add the virtual path to the master page, or the class in the TypeName
. You can then access everything with intellisense.
您可以使用两种方法。第一种是通过使用Page.Master.FindControl('controlID')
. 然后您可以将其转换为您的用户控件的类型。第二种方法是向aspx 页面添加<%@ MasterType VirtualPath="">
OR<%@ MasterType TypeName=""%>
标记。在VirtualPath
母版页中添加虚拟路径,或TypeName
. 然后,您可以使用智能感知访问所有内容。
回答by Robert C. Barth
There's one other method, and that's by making a public property on the master page that exposes the user control.
还有另一种方法,那就是在母版页上创建一个公开用户控件的公共属性。
回答by Mark Carpenter
Using a public property would work. In the content page's FormLoad method, you could do something like this (VB):
使用公共财产会起作用。在内容页面的 FormLoad 方法中,您可以执行以下操作 (VB):
Dim myMaster as MyMasterPage = CType(Page.Master, MyMasterPage)
myMaster.MyUserControl.Text = "Hello!"
回答by jyothi
first find the user control in the masterpage as below.Then find the control you need to access their property.
首先在母版页中找到用户控件,如下所示。然后找到您需要访问其属性的控件。
UserControl uch = Page.Master.FindControl("ucHeader1") as UserControl;
PlaceHolder phProxylist= ucHeader1.FindControl("phProxy") as PlaceHolder;
DropDownList ddlproxylist1 = ucHeader1.FindControl("ddlProxyList") as DropDownList;
phProxylist.Visible = false;
Hope this helps.
希望这可以帮助。