2009-12-16 127 views
3

我有一個用戶控件接受一個標題屬性。我也想,像這樣用戶控件標記的內部的輸入內HTML(ASP也控制):ASP.NET用戶控件內容

<uc:customPanel title="My panel"> 
    <h1>Here we can add whatever HTML or ASP controls we would like.</h1> 
    <asp:TextBox></asp:TextBox> 
</uc:customPanel> 

我怎樣才能做到這一點?我有title屬性正常工作。

謝謝。

+0

我認爲你不能做到這一點......但是喲可以做到這一點在烏爾用戶控制 – 2009-12-16 04:26:39

+0

的的.ascx你可以指定一個位嗎?在我的ascx文件中,我有<%=title%>和<%=content%>,它可以正常工作,但將自定義HTML傳遞給content屬性是一件很痛苦的事情。 – ademers 2009-12-16 04:29:27

+0

System.Web.UI.UserControl沒有屬性文本框 – 2009-12-16 04:30:58

回答

7

實現一個可擴展面板,實現了作INamingContainer類:

public class Container: Panel, INamingContainer 
{ 
} 

然後,你CustomPanel需要公開類型的容器的屬性和類型的ITemplate的另一個特性:在方法

public Container ContainerContent 
{ 
    get 
    { 
     EnsureChildControls(); 
     return content; 
    } 
} 
[TemplateContainer(typeof(Container))] 
[TemplateInstance(TemplateInstance.Single)] 
public virtual ITemplate Content 
{ 
    get { return templateContent; } 
    set { templateContent = value; } 
} 

然後CreateChildControls(),加入:

if (templateContent != null) 
{ 
    templateContent.InstantiateIn(content); 
} 

而你將會像這樣使用它:

<uc:customPanel title="My panel"> 
    <Content>  
     <h1>Here we can add whatever HTML or ASP controls we would like.</h1> 
     <asp:TextBox></asp:TextBox> 
    </Content> 
</uc:customPanel> 
0

您需要確保EnsureChildControls被調用。通過CreateChildControls基本方法可以實現多種方式,但您可以簡單地執行此操作以獲取要呈現的自定義控件的內部內容。當你需要記住狀態和觸發事件時,它變得更加複雜,但對於純HTML,這應該起作用。

protected override void Render(HtmlTextWriter writer) { 
    EnsureChildControls(); 
    base.Render(writer); 
}