【问题标题】:ASP.NET Custom Control - Naming ContainerASP.NET 自定义控件 - 命名容器
【发布时间】:2010-06-25 13:01:57
【问题描述】:

我有 2 个用户控件,我被用作另一个的容器:

<mc:Container runat="server" ID="container">
   <mc:MyControl runat="server" ID="test">
</mc:Container>

mc 容器有一个名为 content 的默认内部属性,它是 MyControls 的集合。

上面的标记在FormView 内,当我在formview 上调用FindControl 时,它可以找到容器,但找不到测试。

如何让容器控件不创建新的命名容器?

编辑__

当不在FormView 中时,内部控件的 ID 会在设计器中显示为页面的一部分,因此它可以正常工作。

编辑__

这是我的容器vb:

<ParseChildren(True, "Content")> _
Partial Public Class ctrFormContainer
    Inherits System.Web.UI.UserControl

    Private _content As FormControlCollection
    <PersistenceMode(PersistenceMode.InnerDefaultProperty), _
    TemplateInstance(TemplateInstance.Single)> _
    Public Property Content() As FormControlCollection
        Get
            Return _content
        End Get
        Set(ByVal value As FormControlCollection)
            _content = value
        End Set
    End Property

    Protected Overrides Sub CreateChildControls()
        If _content IsNot Nothing Then
            ctrChildren.Controls.Clear()
            For Each i As FormControl In _content
                ctrChildren.Controls.Add(i)
            Next
        End If
        MyBase.CreateChildControls()

    End Sub

    Public Overrides Function FindControl(ByVal id As String) As System.Web.UI.Control
        Return MyBase.FindControl(id)
    End Function

    Public Class FormControlCollection
        Inherits List(Of FormControl)
    End Class
End Class

【问题讨论】:

    标签: asp.net user-controls


    【解决方案1】:

    简短的回答 - 你不能。 UserControl 类继承自 TemplateControl,它实现了 INamingContainer 接口。这意味着所有用户控件都是命名容器,在嵌套的情况下,FindControl 将不起作用。

    解决方案是在层次结构中实现对控件的递归搜索,如果在最顶层找不到控件,则遍历每个项目的 Controls 集合。这是一个示例实现: http://stevesmithblog.com/blog/recursive-findcontrol/

    【讨论】:

    • 谢谢,我只知道 asp:PlaceHolder 还继承了实现 INamingContainer 的 Control 并且不会创建新的命名容器......我想知道 PlaceHolder 类是如何做到的
    • PlaceHolder 继承 Control,而不是 UserControl 或 TemplateControl。控件不实现 INamingContainer。打开 Reflector 自己看看,差别很大。
    • 哇,你说得对,我看错了,Usercontrol继承了模板控件,还实现了INamingContainer……我看错了,谢谢。因此,应该使用自定义控件而不是用户控件来执行此操作。谢谢
    • 没错。如果您不使用用户控件,一切都应该没问题。
    猜你喜欢
    • 2010-09-23
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 2011-06-15
    • 2011-03-17
    • 1970-01-01
    相关资源
    最近更新 更多