代码之家  ›  专栏  ›  技术社区  ›  s15199d

从用户控件访问父页属性

  •  8
  • s15199d  · 技术社区  · 15 年前

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

    下面是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的成员”

    请再见!

    2 回复  |  直到 15 年前
        1
  •  9
  •   Tim Schmelter    15 年前

    您可以在将页强制转换为名为“u Default”的实际实现时访问该属性。

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

    通常,您会将控制器(页面)的ID提供给用户控件。

    所以在UserControl中定义一个属性并从页面设置它。 这样,UserControl仍然可以在其他页面中工作。

        2
  •  1
  •   Joel Etherton    15 年前

    因为用户控件不属于页,所以除非从包含页显式地在用户控件中设置一个属性,或者创建一个循环遍历所有父对象的递归函数,直到找到类型为的对象,否则无法直接访问它 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
    

    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
    

    编辑:您也不能直接访问此属性,因为它不存在于类型内 系统.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
    
    推荐文章