我想创建一个具有子项的自定义/用户控件.
例如,我希望我的控件具有以下标记:
<div runat="server" id="div">
<label runat="server" id="label"></label>
<div class="field">
<!-- INSERT CHILDREN HERE -->
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
当我想在页面上使用它时,我只需:
<ctr:MyUserControl runat="server" ID="myControl">
<span>This is a child</span>
<div runat="server" id="myChild">And another <b>child</b>
</ctr:MyUserControl>
Run Code Online (Sandbox Code Playgroud)
我的用户控件中的子控件将被插入到我的用户控件中.完成此任务的最佳方法是什么?
该功能类似于asp:PlaceHolder,但我想添加更多选项以及其他标记等.子页面控件仍然需要能够被页面访问.(在上面的例子中,页面上应该有myChild控件)
编辑------
它可以是模板控件,只要它允许我引用页面上的子项.
我刚才问了类似的问题.看到这里.
我相信你必须使用ITemplate作为InnerProperty:
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content
{
get
{
return _content;
}
set
{
_content = value;
}
}
private ITemplate _content;
Run Code Online (Sandbox Code Playgroud)
然后覆盖控件的CreateChildControls方法:
protected override void CreateChildControls()
{
if (this.Content != null)
{
this.Controls.Clear();
this.Content.InstantiateIn(this);
}
base.CreateChildControls();
}
Run Code Online (Sandbox Code Playgroud)
使用a有什么害处ITemplate您可以将它与现有标记结合使用,并在Content属性中编写您想要的任何HTML .
| 归档时间: |
|
| 查看次数: |
6186 次 |
| 最近记录: |