加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – ASP.NET:构建以列表作为参数的用户控件?

发布时间:2020-12-16 01:33:52 所属栏目:百科 来源:网络整理
导读:如何构建一个以列表作为参数的用户控件,即: foo:TabMenu runat="server"TabsTab Label="Tab1" PanelId="pnlTab1"/Tab Label="Tab2" PanelId="pnlTab2"/Tab Label="Tab3" PanelId="pnlTab3"//Tabs/foo:TabMenu 解决方法 你需要这样的东西.一切都很好,但你必
如何构建一个以列表作为参数的用户控件,即:

<foo:TabMenu runat="server">
<Tabs>
<Tab Label="Tab1" PanelId="pnlTab1"/>
<Tab Label="Tab2" PanelId="pnlTab2"/>
<Tab Label="Tab3" PanelId="pnlTab3"/>
</Tabs>
</foo:TabMenu>

解决方法

你需要这样的东西.一切都很好,但你必须完成TabCollection类.

编辑:原谅我,我没有测试代码.无论如何发现一些问题所以解决了他们.

用户控件

[ParseChildren(true,"Tabs"),PersistChildren(false)]
public partial class TabMenu : UserControl
{

    private TabCollection _tabs;

    [Browsable(false),PersistenceMode(PersistenceMode.InnerProperty),MergableProperty(false)]
    public virtual TabCollection Tabs
    {
        get
        {
            if (this._tabs == null)
                this._tabs = new TabCollection(this);
            return this._tabs;
        }
    }

    protected override ControlCollection CreateControlCollection()
    {
        return new TabMenuControlCollection(this);
    }

}

标签

public class Tab : HtmlGenericControl
{

    public string Label
    {
        get { return (string)ViewState["Label"] ?? string.Empty; }
        set { ViewState["Label"] = value; }
    }

}

TabCollection

public class TabCollection : IList,ICollection,IEnumerable
{

    private TabMenu _tabMenu;

    public TabCollection(TabMenu tabMenu)
    {
        if (tabMenu == null)
            throw new ArgumentNullException("tabMenu");

        this._tabMenu = tabMenu;
    }

    public virtual int Add(Tab tab)
    {
        if (tab == null)
            throw new ArgumentNullException("tab");

        this._tabMenu.Controls.Add(tab);

        return this._tabMenu.Controls.Count - 1;
    }

    int IList.Add(object value)
    {
        return this.Add((Tab)value);
    }

    // You have to write other methods and properties as Add.

}

TabMenuControlCollection

public class TabMenuControlCollection : ControlCollection
{

    public TabMenuControlCollection(TabMenu owner) : base(owner) { }

    public override void Add(Control child)
    {
        if (child == null)
            throw new ArgumentNullException("child");

        if (!(child is TabMenu))
            throw new ArgumentException("The TabMenu control can only have a child of type 'Tab'.");

        base.Add(child);
    }

    public override void AddAt(int index,Control child)
    {
        if (child == null)
            throw new ArgumentNullException("child");

        if (!(child is TabMenu))
            throw new ArgumentException("The TabMenu control can only have a child of type 'Tab'.");

        base.AddAt(index,child);
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读