如何在C#.NET您“克隆”器WebControls?如何在、NET、WebControls

2023-09-06 14:53:36 作者:一路荒凉如歌

我的基本问题是,在.NET中,我怎么克隆器WebControls?

My basic question is, in .NET, how do I clone WebControls?

我想建立一个自定义标签,它可以产生其子的多个副本。 最终,我打算建立类似于JSP / Struts的标签。

I would like to build a custom tag, which can produce multiple copies of its children. Ultimately I intend to build a tag similar to in JSP/Struts.

不过第一关我是复制/克隆一个控制的内容的能力。

But the first hurdle I have is the ability to duplicate/clone the contents of a control.

考虑这个虚构的例子;

Consider this rather contrived example;

<custom:duplicate count="2">
    <div>
        <p>Some html</p>
        <asp:TextBox id="tb1" runat="server" />
    </div>
</custom:duplicate>

的HTML标记是输出会是这样的,

The HTML markup which is output would be something like,

<div>
    <p>Some html</p>
    <input type="text" id="tb1" />
</div>
<div>
    <p>Some html</p>
    <input type="text" id="tb1" />
</div>

注:我知道我有ID重复,后来我想出了一个解决方案,即的

那么,我们本来就是我有3个孩子(我认为)自定义控件 - 文字的控制,一个TextBox控件,另一个文本控件

So what we would have is my custom control with 3 children (I think) - a literal control, a TextBox control, and another literal control.

在这个例子中,我曾经说过'计数= 2那么控制应该做的是输出/渲染它的孩子的两倍。

In this example I have said 'count=2' so what the control should do is output/render its children twice.

什么我希望做的是写一些的OnInitcode这确实是这样的:

What I would hope to do is write some "OnInit" code which does something like:

List<WebControl> clones;
for(int i=1; i<count; i++)
{
    foreach(WebControl c in Controls) 
    {
        WebControl clone = c.Clone();
        clones.Add(clone);
    }
}

Controls.AddRange(clones);

不过,据我所知,器WebControls没有实现ICloneable,所以它不可能克隆它们以这种方式。

However, as far as I can tell, WebControls do not implement ICloneable, so its not possible to clone them in this way.

任何想法如何,我可以克隆器WebControls?

Any ideas how I can clone WebControls?

推荐答案

什么是错用一个中继器,并结合哑了数据源。它会复制模板的控制和处理ID创建和一切。

What's wrong with using a Repeater and binding a dud data source. It'll duplicate the templated controls and handle the ID creation and all.