如何初始化内联Control

时间:2016-07-26 19:48:39

标签: c# asp.net initialization

我真的不知道我不能这样做

    Panel panel = new Panel()
    {
        Controls = new ControlCollection(this)
        {
            new Panel()
            {
                Controls = new ControlCollection(this)
                {
                    new Label() { Text = "Label1" },
                    new Label() { Text = "Label2" }
                }
            }
        }
    };

因为,在这种特殊情况下,我得到Property or indexer 'Control.Controls' cannot be assigned to -- it is read only

相反,我必须这样做

    Panel innerPanel = new Panel();
    innerPanel.Controls.Add(new Label() { Text = "Label1" });
    innerPanel.Controls.Add(new Label() { Text = "Label2" });
    Panel panel = new Panel();
    panel.Controls.Add(innerPanel);

任何聪明的方法都可以让代码样式的树工作吗?

1 个答案:

答案 0 :(得分:2)

只需省略ControlCollection构造函数调用:

Panel panel = new Panel
{
    Controls =
    {
        new Panel
        {
            Controls =
            {
                new Label { Text = "Label1" },
                new Label { Text = "Label2" }
            }
        }
    }
};

这会将PanelLabel子控件添加到ControlCollection属性返回的现有 Controls对象中,而不是创建新的ControlCollection个对象。