Custom ASP.NET Container Control

前端 未结 8 1915
醉话见心
醉话见心 2020-12-14 20:50

I\'ve been trying to create a custom control that works exactly like the Panel control except surrounded by a few divs and such to create a rounded box look. I haven\'t been

8条回答
  •  星月不相逢
    2020-12-14 21:20

    There are already quite a few answers here, but I just wanted to paste the most basic implementation of this without inheriting from Panel class. So here it goes:

    using System.ComponentModel;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    [ToolboxData("<{0}:SimpleContainer runat=server>")]
    [ParseChildren(true, "Content")]
    public class SimpleContainer : WebControl, INamingContainer
    {
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(SimpleContainer))]
        [TemplateInstance(TemplateInstance.Single)]
        public virtual ITemplate Content { get; set; }
    
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            // Do not render anything.
        }
    
        public override void RenderEndTag(HtmlTextWriter writer)
        {
            // Do not render anything.
        }
    
        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write("
    "); this.RenderChildren(output); output.Write("
    "); } protected override void OnInit(System.EventArgs e) { base.OnInit(e); // Initialize all child controls. this.CreateChildControls(); this.ChildControlsCreated = true; } protected override void CreateChildControls() { // Remove any controls this.Controls.Clear(); // Add all content to a container. var container = new Control(); this.Content.InstantiateIn(container); // Add container to the control collection. this.Controls.Add(container); } }

    Then you can use it like this:

    
        
            
    
            
        
    
    

    And from codebehind you can do things like this:

    this.btnSubmit.Text = "Click me!";
    this.txtName.Text = "Jack Sparrow";
    

提交回复
热议问题