ASP.NET自定义服务器控件 - 制作单选按钮列表列表

时间:2015-05-06 15:10:06

标签: c# asp.net

这是我的尝试:

[DefaultProperty("Caption")]
    [ToolboxData("<thp:RadioButtonListList runat=server></thp:RadioButtonListList>")]
    public class RadioButtonListList : WebControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Caption
        {
            get
            {
                String s = (String)ViewState["Caption"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["Caption"] = value;
            }
        }

        [DefaultValue(new List<RadioButtonList>())]
        [Localizable(true)]
        public List<RadioButtonList> Items
        {
            get
            {
                List<RadioButtonList> l = (List<RadioButtonList>)ViewState["Items"];
                return ((l == null) ? new List<RadioButtonList>() : l);
            }

            set
            {
                ViewState["Items"] = value;
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write("<div class=\"btn-group-vertical\" role=\"group\" aria-label=\"" + this.Caption + "\">");
            foreach (var item in this.Items) {
                item.RenderControl(output);
            }
            output.Write("</div>");
        }
    }

当我将Items属性分配为默认值List()时,我收到以下错误:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

我希望我在这里尝试做的很明确......我只是不明白为什么我会收到这个错误......

1 个答案:

答案 0 :(得分:2)

你的问题在于这一行:

[DefaultValue(new List<RadioButtonList>())]

new List<RadioButtonList>()不是编译时常量。