从用户控件访问父页面属性

时间:2010-11-04 14:28:32

标签: asp.net vb.net

尝试从我的用户控件上的父页面访问属性。

这是我的default.asp代码隐藏的开始:

Partial Class _Default
     Inherits System.Web.UI.Page

     Private _selectedID As String = "74251BK3232"

     Public Property SelectedID() As String
          Get
               Return _selectedID 
          End Get
          Set(ByVal value As String)
               _selectedID = value
          End Set
     End Property

这是我的用户控制代码隐藏的开始:

Partial Class ctrlAddAttribute
    Inherits System.Web.UI.UserControl
     Dim selectedID As String = Me.Parent.Page.selectedID()

我收到错误“selectedID不是System.Web.UI.Page的成员”

请adivse!

2 个答案:

答案 0 :(得分:9)

当您将Page转换为名为_Default的实际实现时,您可以访问该属性。

Dim selectedID As String = DirectCast(Me.Page,_Default).selectedID()

但这不是Usercontrol(可重用性)的目的。 通常,您可以将Controller(页面)中的ID提供给UserControl。

因此,在UserControl中定义属性并从页面设置它。 通过这种方式,UserControl仍然可以在其他页面中使用。

答案 1 :(得分:1)

因为用户控件不属于该页面,所以除非您从包含页面在usercontrol中显式设置属性或创建循环遍历所有父对象的递归函数,否则无法直接访问它。它找到了System.Web.UI.Page类型的对象。

对于第一个,您可以在用户控件中使用属性(我使用名为ParentForm的属性完成此操作):

Private _parentForm as System.Web.UI.Page
Public Property ParentForm() As System.Web.UI.Page  ' or the type of your page baseclass
    Get
        Return _parentForm
    End Get
    Set
        _parentForm = value
    End Set
End Property

在“父级”页面中,您应尽早在事件中设置此属性。我更喜欢使用PreLoad,因为它在加载之前(因此在大多数其他控件需要它时可用)和init之后。

Protected Sub Page_PreLoad(ByVal sender as Object, ByVal e as EventArgs) Handles Me.PreLoad
    Me.myUserControlID.ParentForm = Me
End Sub

您还可以通过父控件编写函数巨魔来查找页面。以下代码未经测试,因此可能需要调整,但这个想法很合理。

Public Shared Function FindParentPage(ByRef ctrl As Object) As Page
    If "System.Web.UI.Page".Equals(ctrl.GetType().FullName, StringComparison.OrdinalIgnoreCase) Then
        Return ctrl
    Else
        Return FindParentPage(ctrl.Parent)
    End If
End Function

编辑:您也无法直接访问此属性,因为它在System.Web.UI.Page类型中不存在。正如@Tim Schmelter建议的那样,您可以尝试将页面强制转换为特定页面类型_Default,或者如果这是您的许多页面常见的内容,则可能需要创建基页类并将您的属性包括在内那个班。然后,您可以继承此类而不是System.Web.UI.Page

Public Class MyBasePage
    Inherits System.Web.UI.Page

    Public Property SelectedID() as Integer
        ...
    End Property
End Class

然后在页面中:

Partial Class _Default
    Inherits MyBasePage

    ...

End Class