自定义用户控件中的ASP嵌套标签
时间:2020-03-06 14:35:56 来源:igfitidea点击:
我刚刚开始使用cand中的"自定义用户控件",我想知道是否有关于如何编写一个接受嵌套标签的示例。例如,当我们创建" asp:repeater"时,可以为" itemtemplate"添加一个嵌套标签。
任何帮助表示赞赏!
干杯
解决方案
不久前,我写了一篇有关此的博客文章。简而言之,如果我们具有带有以下标记的控件:
<Abc:CustomControlUno runat="server" ID="Control1"> <Children> <Abc:Control1Child IntegerProperty="1" /> </Children> </Abc:CustomControlUno>
我们需要控件中的代码遵循以下原则:
[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; } }
我的猜测是我们正在寻找类似的东西吗? http://msdn.microsoft.com/en-us/library/aa478964.aspx
标签已被删除或者不可见,因此无法真正为我们提供帮助。
我关注了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>
然后在代码中,将控件的" 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); } } }