简体   繁体   English

我可以在Web用户控件中使用parent(网页)属性吗?

[英]Can I use parent(web page) property in web user control?

How can I use parent(web page) property in web user control? 如何在Web用户控件中使用parent(网页)属性?

One more question:- How can I access the shared class(ie class in App_Code folder) property in web user control. 另一个问题:-如何访问Web用户控件中的共享类(即App_Code文件夹中的类)属性。

Thanks 谢谢

You can use this.Page in asp.net user control to refer to page and it will always give you page in which that control is added. 您可以在asp.net用户控件中使用this.Page来引用页面,它将始终为您提供添加了该控件的页面。

You can access any public class declared in App_code folder directly in any user control without problem. 您可以直接在任何用户控件中访问App_code文件夹中声明的任何公共类,而不会出现问题。 Be careful of namespace and make sure to compile your project if you are having issues to access the class. 注意命名空间,如果访问类时遇到问题,请确保编译项目。

You could but I am not sure it would be a clean / full OOP approach, how about setting a public property or calling a public method of your user control from the page passing to it the value you need to use in the control? 您可以但我不确定这将是一种干净/完整的OOP方法,如何设置公共属性或从传递给该控件的页面调用您需要在控件中使用的值的方式调用用户控件的公共方法?

this because the page hosting the control should be generic and is the page which contains the control not the other way round. 这是因为托管控件的页面应该是通用的,并且包含控件的页面不是相反的。

If this does not fit you, then you can take the control's Page property and cast it to the class of your page then you will be able to access its property but this will make your control specific instead of generic and it will only work when the control is hosted in pages of that exact type/class. 如果这不适合您,则可以使用控件的Page属性并将其强制转换为页面的类,然后您将可以访问其属性,但这将使控件特定而不是通用,并且仅当控件托管在该确切类型/类的页面中。

You have to mark the property as Public. 您必须将该属性标记为“公共”。

var myVar = ((ParentPageClass)this.Page).YourProperty;

To access the shared class you have to specify the namespace of that class: 要访问共享类,您必须指定该类的名称空间:

YourProject.SomeNamespace.YourClass

or to include the namespace in your .ascx.cs file 或在.ascx.cs文件中包含名称空间

using YourProject.SomeNamespace;

It's a cleaner aproach to pass the parameter to the user control from the parent page. 将参数从父页面传递给用户控件是一种更简洁的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM