自定义用户控件中的ASP嵌套标记

Sta*_*ony 9 .net c# asp.net custom-server-controls

我刚刚开始使用C#中的自定义用户控件,我想知道是否有任何关于如何编写接受嵌套标签的示例?

例如,在创建时,可以为其asp:repeater添加嵌套标记itemtemplate.

Rob*_*Rob 16

我前段时间写了一篇关于此的博文.简而言之,如果您有一个带有以下标记的控件:

<Abc:CustomControlUno runat="server" ID="Control1">
    <Children>
        <Abc:Control1Child IntegerProperty="1" />
    </Children>
</Abc:CustomControlUno>
Run Code Online (Sandbox Code Playgroud)

您需要控件中的代码遵循以下方式:

[ParseChildren(true)]
[PersistChildren(true)]
[ToolboxData("<{0}:CustomControlUno runat=server></{0}:CustomControlUno>")]
public class CustomControlUno : WebControl, INamingContainer
{
    private Control1ChildrenCollection _children;

    [PersistenceMode(PersistenceMode.InnerProperty)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public Control1ChildrenCollection Children
    {
        get
        {
            if (_children == null)
            {
                _children = new Control1ChildrenCollection();
            }
            return _children;
        }
    }
}

public class Control1ChildrenCollection : List<Control1Child>
{
}

public class Control1Child
{
    public int IntegerProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 链接博客帖子作为答案的问题是网站何时死亡.我正在打字的情况是这样的.因此我看不出答案. (3认同)

Guð*_*r H 6

我跟随Rob的博客文章,做了一个略微不同的控制.控件是有条件的,就像if子句一样:

<wc:PriceInfo runat="server" ID="PriceInfo">
    <IfDiscount>
        You don't have a discount.
    </IfDiscount>
    <IfNotDiscount>
        Lucky you, <b>you have a discount!</b>
    </IfNotDiscount>
</wc:PriceInfo>
Run Code Online (Sandbox Code Playgroud)

在代码中,然后将HasDiscount控件的属性设置为布尔值,该布尔值决定呈现哪个子句.

与Rob的解决方案的最大区别在于,控件中的子句实际上可以保存任意HTML/ASPX代码.

以下是控件的代码:

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

namespace WebUtilities
{
    [ToolboxData("<{0}:PriceInfo runat=server></{0}:PriceInfo>")]
    public class PriceInfo : WebControl, INamingContainer
    {
        private readonly Control ifDiscountControl = new Control();
        private readonly Control ifNotDiscountControl = new Control();

        public bool HasDiscount { get; set; }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Control IfDiscount
        {
            get { return ifDiscountControl; }
        }

        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Control IfNotDiscount
        {
            get { return ifNotDiscountControl; }
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            if (HasDiscount)
                ifDiscountControl.RenderControl(writer);
            else
                ifNotDiscountControl.RenderControl(writer);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)