.net - 有没有一种方法可以将内部控件放入ASP.NET自定义控件中?

标签 .net asp.net asp.net-controls

我想做类似的事情(更新示例):

<uc:Tabs>
  <Tab Name="A handy tab">
    <Node Url="~/Default.aspx" />
    <Node Url="~/Node2.aspx" />
  </Tab>      
  <Tab Name="Another handy tab">
    <Node Url="~/Neato.aspx" />
    <Node Url="~/Node3.aspx" />
    <Node Url="~/Node4.aspx" />
  </Tab>
<uc:Tabs>

可能的?有教程或操作方法吗?我不知道该搜索什么,或者称什么,所以到目前为止还没有找到任何东西。内部控件?内部收藏的东西...?

最佳答案

使用ParseChildrenAttributePersistChildrenAttribute属性:

[ParseChildren(false)]
[PersistChildren(true)]
public class MyControl : UserControl { }

这将导致您将任何控件放入引用中:
<uc:MyControl runat="server">
  <asp:TextBox runat="server" />
<uc:MyControl>

要追加到UserControl内容的Controls集合的末尾。

但是,如果要具有控件集合,则可能应该使用服务器控件而不是用户控件。对于这样的控件:
<foo:TabControl runat="server">
    <Tabs>
        <foo:Tab CssClass="myclass" Title="Hello World" />
    </Tabs>
</foo:TabControl>

您需要一个具有Tabs属性的Control类。 Tabs属性应为Collection;并且应包含Tab类型的对象。我在这里创建了三个类:
[ParseChildren(true, "Tabs")]
public class TabControl: WebControl, INamingContainer
{
    private TabCollection _tabs;

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
    public TabCollection Tabs
    {
        get
        {
            if (_tabs == null)
            {
                _tabs = new TabCollection();
            }
            return _tabs;
        }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        foreach (Tab tab in Tabs)
        {
            writer.WriteBeginTag("div");
            writer.WriteAttribute("class", tab.CssClass);
            writer.Write(HtmlTextWriter.TagRightChar);
            writer.Write("this is a tab called " + tab.Title);
            writer.WriteEndTag("div");
        }
    }
}

和选项卡类:
public class Tab
{
    public string CssClass { get; set; }
    public string Title { get; set; }
}

和选项卡集合:
public class TabCollection : Collection<Tab> { }

关于.net - 有没有一种方法可以将内部控件放入ASP.NET自定义控件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/604620/

相关文章:

ASP.NET MVC 使用类型化模型将模型双向数据绑定(bind)到单选按钮列表

c# - 处理应用程序重新设计

asp.net - 如何在 ASP.NET 页面上注册自定义服务器控件

c# - 如何禁用 ASP.NET 页面中的所有控件?

c# - 如何使 switch 语句更面向对象?

c# - EF 4,如何添加部分类

asp.net - UseJwtBearerAuthentication 返回 401

asp.net - 在已创建的 DataTable 对象上使用 SELECT DISTINCT?

c# - Long 来自字符列表 C#

c# - 图像未绘制在正确的位置