2010-03-15 136 views
9

多個控制集合我已經建立一個自定義的WebControl,它具有以下結構:渲染在ASP.NET自定義控件

<gws:ModalBox ID="ModalBox1" HeaderText="Title" runat="server"> 
    <Contents> 
     <asp:Label ID="KeywordLabel" AssociatedControlID="KeywordTextBox" runat="server">Keyword: </asp:Label><br /> 
     <asp:TextBox ID="KeywordTextBox" Text="" runat="server" /> 
    </Contents> 
    <Footer>(controls...)</Footer> 
</gws:ModalBox> 

控制包含兩個的ControlCollection屬性,「內容」和「尾」。從來沒有試圖建立與多個控制集合控制,但解決它像這樣(簡化):

[PersistChildren(false), ParseChildren(true)] 
public class ModalBox : WebControl 
{ 
    private ControlCollection _contents; 
    private ControlCollection _footer; 

    public ModalBox() 
     : base() 
    { 
     this._contents = base.CreateControlCollection(); 
     this._footer = base.CreateControlCollection(); 
    } 

    [PersistenceMode(PersistenceMode.InnerProperty)] 
    public ControlCollection Contents { get { return this._contents; } } 

    [PersistenceMode(PersistenceMode.InnerProperty)] 
    public ControlCollection Footer { get { return this._footer; } } 

    protected override void RenderContents(HtmlTextWriter output) 
    { 
     // Render content controls. 
     foreach (Control control in this.Contents) 
     { 
      control.RenderControl(output); 
     } 

     // Render footer controls. 
     foreach (Control control in this.Footer) 
     { 
      control.RenderControl(output); 
     } 
    } 
} 

但是它似乎正確地呈現,它不會了,如果我加入一些asp.net標籤和輸入工作屬性內的控件(參見上面的asp.net代碼)。我將得到HttpException:

無法找到具有標識'KeywordLabel'與 關聯的id爲'KeywordTextBox'的控件。

有些可以理解,因爲標籤出現在controlcollection的文本框之前。但是,使用默認的asp.net控件它確實有效,那麼爲什麼這不起作用呢?我究竟做錯了什麼?在一個控件中是否可以有兩個控件集合?我應該以不同的方式呈現嗎

感謝您的回覆。

回答

2

您可以使用兩種面板爲你的兩個家長控制集合(並且它們會提供分組和改進的可讀性)。將每個集合中的控件添加到相應面板的Controls集合中,並在Render方法中調用每個面板的Render方法。面板將自動呈現他們的子女,並將爲他們提供自己的名字空間,因此,您可以在不同面板中使用類似ID的控件。

+0

是的,這將工作! – 2010-09-11 09:16:16

1

我不確定這會起作用。如果您使用模板,但您可以使控件正確呈現輸出。

首先,定義一個類被用作容器控件類型:

public class ContentsTemplate : Control, INamingContainer 
{ 
} 

而現在的自定義控件:

[PersistChildren(false), ParseChildren(true)] 
public class ModalBox : CompositeControl 
{ 

    [PersistenceMode(PersistenceMode.InnerProperty)] 
    [TemplateContainer(typeof(ContentsTemplate))] 
    public ITemplate Contents { get; set; } 

    [PersistenceMode(PersistenceMode.InnerProperty)] 
    [TemplateContainer(typeof(ContentsTemplate))] 
    public ITemplate Footer { get; set; } 

    protected override void CreateChildControls() 
    { 
    Controls.Clear(); 

    var contentsItem = new ContentsTemplate(); 
    Contents.InstantiateIn(contentsItem); 
    Controls.Add(contentsItem); 

    var footerItem = new ContentsTemplate(); 
    Footer.InstantiateIn(footerItem); 
    Controls.Add(footerItem); 
    } 

} 
+0

我遇到了與op類似的問題,這不起作用。您不能在ITemplates內部引用任何控件,因爲它們沒有正確實例化,這違背了此類控件的目的。 – mattmanser 2010-09-08 08:48:59