1

我正在寻找一个可以在其中容纳标记的 WebControl,并自己动态创建子控件。我遇到的问题是我不能(还)将标记中的控件(参见下面的示例)与我创建的子控件分开。

我知道我需要使用以下 2 个标志设置课程:

[ParseChildren(false)]
[PersistChildren(true)]
public class OuterControl : WebControl
{
  ...
}

示例标记如下所示:

<custom:OuterControl>
  <asp:TextBox ...>
<custom:OuterControl>

RenderContents()中,我需要将一些控件添加到控件树中,进行渲染,然后在特定部分中渲染包装在标记中的控件。例如:

protected override void RenderContents(HtmlTextWriter output)
{
  EnsureChildControls();
  [ Misc work, render my controls ]

  [** Would like to render wrapped children here **]

  [ Possibly other misc work ]
}

如前所述,我可以通过调用RenderChildren()使我的代码创建的控件呈现两次,或者通过删除该行使包装的控件根本不呈现。该死。

想法?

4

1 回答 1

1

当我有类似的要求(围绕提供的控件构建一组标准控件)时,我最终做了这样的事情:

EnsureChildControls();

Control[] currentControls = new Control[Controls.Count];

if (HasControls()) {
  Controls.CopyTo(currentControls, 0);
  Controls.Clear();
}

// Misc work, add my controls, etc, e.g.
Panel contentBox = new Panel { ID = "Content", CssClass = "content_border" };
// at some point, add wrapped controls to a control collection
foreach (Control currentControl in currentControls) {
  contentBox.Controls.Add(currentControl);
}

// Finally, add new controls back into Control collection
Controls.Add(contentBox);

这一直很好。

于 2009-11-05T16:47:02.840 回答