【问题标题】:Difference between a WebControl and a CompositeControl?WebControl 和 CompositeControl 之间的区别?
【发布时间】:2009-10-16 14:31:49
【问题描述】:

我一直在网上寻找一些关于该主题的文章,但我仍然无法弄清楚它们之间的区别。我有下面显示的代码,如果我从 CompositeControl 继承它可以完美地工作,但如果我从 WebControl 继承则不能。 (它们都呈现代码,但只有 CompositeControl 处理事件)

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestLibrary
{
    public class TemplateControl : CompositeControl
    {
        TextBox txtName = new TextBox();
        TextBox txtEmail = new TextBox();
        Button btnSend = new Button();

        private void SetValues()
        {
            btnSend.Text = "Skicka";
        }

        protected override void CreateChildControls()
        {
            SetValues();

            this.Controls.Add(new LiteralControl("Namn: "));
            this.Controls.Add(txtName);
            this.Controls.Add(new LiteralControl("<br />"));
            this.Controls.Add(new LiteralControl("Email: "));
            this.Controls.Add(txtEmail);
            this.Controls.Add(new LiteralControl("<br />"));
            btnSend.Command += new CommandEventHandler(btnSend_Command);
            this.Controls.Add(btnSend);
        }

        void btnSend_Command(object sender, CommandEventArgs e)
        {
            this.Page.Response.Write("Du har nu klickat på skicka-knappen! <br /><br />");                
        }
    }
}

因此,当我单击按钮并将控件呈现为 WebControl 时,什么也没有发生。但是,如果我将 WebControl 更改为 CompositeControl,则会打印出文本。为什么? WebControl 和 CompositeControl 有什么区别?

【问题讨论】:

    标签: c# events composite web-controls composite-controls


    【解决方案1】:

    CompositeControls 执行 INamingContainerWebControls 不执行。

    两者之间有更多区别,但这就是为什么复合控件可以将事件路由到其子控件而 Web 控件不能。您可以通过将您的类声明更改为:

    public class TemplateControl : WebControl, INamingContainer
    

    瞧,您的按钮事件现在将被处理!

    INamingContainer 只是一个标记接口,它告诉 ASP.NET 一个控件包含可能需要独立于其父控件访问的子控件,因此子控件获得了我们 ASP.NET 开发人员已经知道的那些额外漂亮的 ID,并且爱(例如,ctl00$ctl00)。

    如果WebControl 没有实现INamingContainer,则无法保证孩子的 id 是唯一的,因此父母无法可靠地识别它,也无法转发它的事件。

    【讨论】:

      【解决方案2】:

      What is the difference between UserControl, WebControl, RenderedControl and CompositeControl?

      为什么一个人的行为与另一个人不同?因为它们是不同的类型。如果它们是同一类型,就不会有两个。

      【讨论】:

        猜你喜欢
        • 2010-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 2020-05-10
        • 2014-09-20
        • 2010-10-28
        • 2015-10-04
        相关资源
        最近更新 更多