ASP.NET自定义/用户控制带小孩 [英] ASP.NET Custom/User Control With Children

查看:128
本文介绍了ASP.NET自定义/用户控制带小孩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个具有孩子的自定义/用户控件。

I want a create a custom/user control that has children.

例如,我希望我的控制有以下标记:

For Example, I want my control to have the following markup:

<div runat="server" id="div">
    <label runat="server" id="label"></label>
    <div class="field">
        <!-- INSERT CHILDREN HERE -->
    </div>
</div>

而当我想用它在页面上我简单:

and when I want to use it on a page I simply:

<ctr:MyUserControl runat="server" ID="myControl">
    <span>This is a child</span>
    <div runat="server" id="myChild">And another <b>child</b>
</ctr:MyUserControl>

我的用户控件中的子控件将地方插入我的用户控件。什么是实现这一目标的最佳方式?

The child controls inside my user control will be inserted into my user control somewhere. What is the best way to accomplish this?

该功能类似于ASP:占位符,但我想添加一些更多的选择,以及额外的标记和这样的。也子控件仍然需要能够按页进行访问。 (在页面上面的例子中应该有它的myChild控制)

The functionality is similar to a asp:PlaceHolder but I want to add a couple more options as well as additional markup and the such. Also the child controls still need to be able to be accessed by the page. (in the example above the page should have the myChild Control on it)

编辑------

它可以是一个模板控制,只要它让我引用孩子在页面上。

It can be a template control as long as it allows me to reference the children on the page.

推荐答案

我问类似的东西我自己前一阵子。见<一href=\"http://stackoverflow.com/questions/2745886/how-can-i-include-additional-markup-within-a-content-inner-property-of-an-asp-n\">here.

I asked something similar myself a while ago. See here.

我相信你将不得不使用了Itemplate作为InnerProperty:

I believe you will have to use an ITemplate as an InnerProperty:

[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate Content
{
    get
    {
        return _content;
    }
    set
    {
        _content = value;
    }
}
private ITemplate _content;

然后重写控件的CreateChildControls方法:

Then override the CreateChildControls method of your control:

protected override void CreateChildControls()
{
   if (this.Content != null)
   {
      this.Controls.Clear();
      this.Content.InstantiateIn(this);
   }
   base.CreateChildControls();
}

什么是在使用了Itemplate 您可以与您现有的标记结合起来,写你想要的内容中的任何HTML 属性。

What's the harm in using an ITemplate You can combine it with your existing markup and write whatever HTML you want within the Content property.

这篇关于ASP.NET自定义/用户控制带小孩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆